I’m making an image gallery. While working on the feature that brings the image to the full size of the browser window I realized that I can’t specifically set the size of the parent element that the img
belongs to so it won’t play nice / fit how I want it to fit. I generally use the below trick for making images resize nicely while keeping the aspect ratio, staying centered nicely and not flowing over it’s parent element.
.keep-img-ratio {
max-width: 100%;
max-height: 100%;
margin: auto;
}
How do you solve this in a situation where the parent element of the img
will be the size of the window which is dynamic and make the auto margin work?
Edit: When I set img
style to display: block;
it will center horizontally, but not vertically.
2
Answers
I found that this answer mostly gives the behavior I'm looking for. Here
I also reposted it below
If anyone knows a better way then please share.
To center it, you can use the technique shown here: Absolute centering.
To make it as big as possible, give it
max-width
andmax-height
of100%
.To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use
object-fit
.Try this for full screen:
Or this for a variable width: