How to define height of a div as percentage of its variable width

Posted . Visible to the public.

This is useful if, for example, you want to use a background-image that has to scale with the width and the div should only have the height of the picture.

html:

<div class="outer">
  <div class="inner">
  </div>
</div>

css:

.outer {
  width: 100%;
  background-image: image-url('background.png');
  background-size: cover;
}
  
.inner {
  padding-top: 60%;
}

How does it work?

There are several CSS attributes that can handle values as percentage. But they use different other attributes as "reference value" for the calculation. For padding, this "reference value" is the width of the div.
In our example the inner div inherits the width from its parent, outer. The height of outer is auto, therefore as high as its content, inner, which in turn is only its padding as it has no content on its own.

The "naive" approach to use the height attribute with a percentage does not work because the reference value for the height percentage is the parent element's height!


Note: If you only depend on the width of the viewport, you can also use vw:

html:

<div class="background-sizer">
</div>

css:

.background-sizer {
  width: 100%;
  height: 60vw;
  background-image: image-url('background.png');
  background-size: cover;
}
Judith Roth
Last edit
Judith Roth
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2017-06-08 15:54)