Posted about 2 years ago. Visible to the public.

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

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.


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


.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:


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


.background-sizer { width: 100%; height: 60vw; background-image: image-url('background.png'); background-size: cover; }

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Judith Roth
Last edit:
about 2 years ago
by Judith Roth
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Judith Roth to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more