The aspect ratio of the image in the picture
P粉557957970
P粉557957970 2023-08-17 20:24:04
0
1
500
<p>I have an image with a caption like this: </p> <pre class="brush:php;toolbar:false;"><figure> <img src="image.jpg"/> <figcaption>title</figcaption> </figure></pre> <p>I also have <code>img{max-width:100%}</code> in the CSS. </p> <p>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: </p> <pre class="brush:php;toolbar:false;"><figure> <img src="image.jpg" width="100" height="200" style="object-fit:contain"/> <figcaption>title</figcaption> </figure></pre> <p>This is roughly what I want, but when the image is 'letterboxed', the title is quite far from the bottom of the image. </p> <p>Is there a way to get the results I want while keeping the title snug to the bottom of the image? </p>
P粉557957970
P粉557957970

reply all(1)
P粉547362845

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.

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 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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template