Posted 6 months 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.

html:

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

css:

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

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

css:

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

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Author of this card:

Avatar
Judith Roth
Last edit:
6 months 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 makandropedia