下面的解决方案将允许放大和缩小图像。,取决于父框的宽度。
所有图像都有一个固定宽度的父容器。只作示范用途..在生产中,这将是父框的宽度。
此解决方案告诉浏览器以最大可用宽度呈现图像,并将高度调整为该宽度的百分比.parent {
width: 100px;}img {
display: block;
width: 100%;
height: auto;}
This image is originally 400x400 pixels, but should get resized by the CSS:
更理想的解决方案:
有了更好的解决方案,您将能够裁剪图像,而不管其大小,并添加一个背景颜色,以弥补裁剪。.parent {
width: 100px;}.container {
display: block;
width: 100%;
height: auto;
position: relative;
overflow: hidden;
padding: 34.37% 0 0 0; /* 34.37% = 100 / (w / h) = 100 / (640 / 220) */}.container img {
display: block;
max-width: 100%;
max-height: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;}
This image is originally 640x220, but should get resized by the CSS:
对于指定填充的行,需要计算图像的高宽比,例如:640px (w) = 100%220px (h) = ?640/220 = 2.909100/2.909 = 34.37%
顶部填充物=34.37%。