CSS: Make image height of viewport while keeping width 100% and cropping edges if wider than viewport

Issue

I want to create a responsive image that takes up the entire height off the viewport and scales as the viewport changes.

I know that I can set the height with this:

height: 100vmax;

However, I cannot understand how to get the image width to change and effectively crop it’s edges off so that the image stays centred horizontally.

A great example of is Big Green Egg’s website although they use a video and I want to use an image.

It’s worth mentioning that I need to enter this code into a CMS page (Magento 2) so it will sit within a set of other DIVs.

Solution

Try to use “vh” and use text-align on the outer container to center the image:

body {
  text-align: center;
}

img {
  height: 100vh;
}
<img src="http://kingofwallpapers.com/sexy-girl-wallpapers/sexy-girl-wallpapers-002.jpg">

But I would recommend to use background-image instead, since it’s a part of design, not a content:

* {
  margin: 0;
}

.image {
  position: absolute;
  top: 50px;
  bottom: 0;
  left: 0;
  right: 0;
  background: #e0eaec url(http://eskipaper.com/images/mikako-zhang-5.jpg) no-repeat center center / auto 100%;
}

h1 {
  line-height: 50px;
  text-align: center;
}
<h1>&lt;header&gt; goes here</h1>
<div class="image"></div>

Answered By – Mike

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published