Read more

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

Judith Roth
June 08, 2017Software engineer at makandra GmbH

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.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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;
}
Posted by Judith Roth to makandra dev (2017-06-08 17:54)