Mantaining the aspect ratio with vw unit.

Hey there ! I’ve been looking into ways to mantain the aspect ratio of my page container, so probably like any of you who did some research on the subject I found this method wich uses padding-bottom and takes advantage on the fact that it’s percentage is calculated based on the containing block’s width:

W3schools Tutorial

But recently I found out about the vw - 1% of Viewport Width and vh - 1% of Viewport Height units [Source].

Now I can have access to the width of my container without having to use the padding trick ! So to keep my container on 16:9 aspect ratio all I need to do is:

<body>
  <div id="container">

   </div>
</body>

If the container width is set to 100%:

#container{
  width: 100%;
  height: 56.25vw; //Or 56.25% based on the viewport width. 
  background: tomato;
}

Now if the container doesn’t take up all the viewport width you need to take it into account, since vw is based on the viewport not the container.

#container{
  width: 80%;
  height: calc(80vw / (16 / 9));/The container width is 80% based on the viewport width or 80vw
  background: tomato;
}

PS: I wanted to share the information but I’m not used to writing this articles and my english isn’t good, so feel free to edit the post if you want. Also, if you know about other ways to do it share it in the coments !

2 Likes

This is a great post! Thanks for sharing with others :slight_smile:

I’ve never seen 16:9 used in calc before, that’ll be an excellent expression using CSS variables, thanks.

1 Like