Search code examples
htmlcssaspect-ratio

CSS - Image Full Screen, but will maintain aspect ratio


How do I get an image to fill the full screen (note there is stuff below it - think of it as a header in a page that fills the whole screen) but maintains its aspect ratio, either overspilling on the width or oversplilling on the height.

I thought it would be:

<img class="w3-image" src="./images/img1.jpg" style="min-width:100vw; max-height:100vh; background-position: center; background-repeat: no-repeat;" />

But that does not work. The aspect ratio fails.


Solution

  • Insert it as a background to an element instead, with background-size: cover; and the element with height: 100vh.