The aspect ratio of the image in the picture
P粉557957970
2023-08-17 20:24:04
<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>
If you are using
To fix this problem, you just need to set the height to "auto".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 towidth: 100px
andheight: 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.
object-fit: contain
. You can learn about other options
here, but maybe you want to set the width/height of the figureelement and let the image fill that space. In this case you can do this: