I am trying to make an image fit the browser window in relation to its height and respond dynamically to window size.
I need the image aspect ratio to stay the same but the image can be ,larger than its originally resolution if viewed on large screens.
I don't want the image to spill outside of the screen and create a scolling effect.
The image must stay centered inside is container both vertically and horizontally.
Here is an example of what I am trying to achieve.
It is not clear what you tried so far and we don't see any code. I'll try to answer anyway and perhaps it'll help you.
First of all, when you working with responsive layouts, always try to size your elements with viewport height and width
. This helps you keep your content relative to the browser size - no matter if resized nor how large the screen is.
This code might help you insert a responsive image to your site:
div {
width:80vw;
height:80vh;
}
img {
max-width:100%;
height:auto;
max-height:100%;
}
Working example here
In this example is div
sized 80% of both window's height and width, so it never exceeds the viewport. Max. measures of img
are 100% of the div
and height:auto;
secures that it preserves its aspect ratio. Image then fits a div to the max allowed. You can comfortably center the image by setting display:table-cell; vertical-align:middle; text-align:center;
to the DIV.
Another solution would be:
background-image:url(' ');
background-size:contain;
background-repeat:no-repeat;
background-position:center;
Check it out here
Using the object-fit
CSS property, you can do it without a container:
img {
height: 100vh;
width: 100%;
object-fit: contain;
}
See the browser support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With