Read more

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

Deleted user #4117
June 08, 2017Software engineer

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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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 to makandra dev (2017-06-08 17:54)