The aspect ratio of the image in the picture
P粉557957970
P粉557957970 2023-08-17 20:24:04
0
1
418

I have an image with a caption like this:

title

I also have img{max-width:100%} in the CSS.

I want to set both the width and height of an image and maintain its aspect ratio when the width decreases below its set value. So, I tried code like this:

title

This is roughly what I want, but when the image is 'letterboxed', the title is quite far from the bottom of the image.

Is there a way to get the results I want while keeping the title snug to the bottom of the image?

P粉557957970
P粉557957970

reply all (1)
P粉547362845

If you are usingobject-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 towidth: 100pxandheight: 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 #figureelement.

To fix this problem, you just need to set the height to "auto".

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 optionshere, but maybe you want to set the width/height of thefigureelement 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; }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!