I have an image with a caption like this:
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:
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?
If you are using
To fix this problem, you just need to set the height to "auto". 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 thanobject-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 thefigureelement and let the image fill that space. In this case you can do this: