P粉5473628452023-08-18 00:54:51
If you are using object-fit: contain
, then the original aspect ratio of the image is already preserved because the entire image must fit into its parent element. So, if the original width of the image is 100px and the height is 150px, and you set the image to width: 100px
and height: 200px
, the height of the image is still 150px, but in ## An additional 25px of space will be added to the top and bottom of the #figure element.
img { // 为了可读性,将您的样式声明移到这里 width: 100px; max-width: 100%; height: auto; object-fit: contain; }Now, if you actually want to define the width and height, and force the image to fit into those dimensions, you should use something other than
object-fit: contain. You can learn about other options
here, but maybe you want to set the width/height of the figure element and let the image fill that space. In this case you can do this:
figure { display: block; width: 100px; max-width: 100%; height: 200px; } img { width: 100%; height: 100%; object-fit: cover; background: blue; }