We often create games at work which need a fixed aspect ratio, to suit the art style and game mechanics.

TLDR; set the max-width to a viewport height unit

You can fill a screen relatively easily. In our case, lets create a div with a class of content.

  html, body{
  height: 100%;
  overflow: hidden;

  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;

This fills the screen, but the issue with this scaling is the same page will look completely different on different size screens:


NB: this is sometimes ideal!

So, how can we fix it to an aspect ratio? Well, first of all we need an aspect ratio div (what's that? You want to try my aspect ratio div calculating pen? All yours!). You can make a div an aspect ratio, by making an element inside it have a padding-bottom as a percentage.

  <div class="aspect">
  <div class="content"></div>


If you want to make it 16:9 you can do something like the following:

  padding-bottom: (9 / 16) * 100%;

Great. But on really shallow (screens with a small height, or iframes like this one above) that div is going to overflow (you can't scroll as the body has overflow: hidden on it). We could give it a max-height... but the height is based on the width of the div.

Oh boy, this is confusing. If the height is based on the width, and its too high, perhaps there is a way to give the div a max-width, based on the height.

There is! Lets give the wrapper a max-width of a viewport height unit. What should that unit be? The aspect width divided by the aspect height:

  $w: 16;
$h: 9;

  width: 100%;
  max-width: $w / $h *  100vh;
  position: relative;
    content: '';
    display: block;
    padding-bottom: ($h / $w) * 100%;

Lets see that all together!

Resize to your hearts content, that div will stay 16:9. If the screen goes wider than, then it will lock height.

Here's a live view for you to really mess around with

6,815 1 77