Categories CSS

Calculating element width in viewport units for responsive design

Post date March 19, 2021

Note: this article is mostly about fixing some problems with Internet Explorer, but the technique may be useful in other cases too.

The other day I had worked on a website with nice big hero image above the content. The image should have taken the whole width on mobile and stay full-width until it reached its own width and stay that wide on bigger screen with white space left and right (centered). Sound easy and in all modern browsers it was. The following CSS did the trick:

img.hero {
  display: block;
  margin-left: auto;
  margin-right: auto;
  max-width: 100%;
  width: auto;
}

However all developers’ favorite browser – Internet Explorer – did not want to cooperate. On bigger screens the image stayed on the left instead of being centered, so I decided to reach for the simplest solution – a media query corresponding to the image width. Assuming the image width is 1500px, the code fixing the problem looked like this:

@media (min-width: 1500px) {
  img.hero {
    width: 1500px;
  }
}

Bigger screens looked fine now, but what about smaller ones? Unfortunately there was a problem – on smaller screens the image was stretched vertically. Luckily, that was an image of known dimensions. So just like writing the first media query with image’s base width hard coded in it, I could write another media query for smaller screens:

@media (max-width: 1500px) {
  img.hero {
   height: 75vw;
  }
}

The easiest way to keep the image’s aspect ratio (width/height ratio) was to go for viewport units. Yes, they are supported by IE! So if the image was supposed to take the whole width and its aspect ratio was 4:3, it meant, that the height needed to be 0.75 x 100vw = 75vw (75% of current viewport’s width).

Conclusion

Internet Explorer has lost support 6 years ago and yet almost every project arrives at some point to the question “how does the website look in IE?”. In my case the problem was not that bad – an image on the left instead of being centered is not the end of the world. The users could still see it and understand the information on it and if the fix was just a few lines of code and it did not break the appearance in other browsers, I was fine with applying it. However, when I face the problems with javascript, that require searching for polyfills, I am far less happy. But that’s an issue for another article.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *