28

Is it possible to implement the following logic usic HTML and CSS?

width: 100%;
height: 30% of width;

What I want to implement: If I decrease the width, the height will also decrease proportionally.

Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
fedor.belov
  • 22,343
  • 26
  • 89
  • 134

3 Answers3

62

Padding %

This can be achieved by giving the element height:0 and padding-bottom:30%.

In all browsers, when padding is specified in %, it's calculated relative to the parent element's width. This can be a very useful feature for Responsive Design.

JSFiddle Demo

In the demo, the blue box at the top of the page is a single div. The height is responsive, and it can contain a variable amount of inline content without increasing the height. It tested fine in IE7/8/9/10, Firefox, Chrome, Safari, and Opera.

.content {
    width: 100%;
    height: 0;
    padding-bottom: 30%;
}
...
<div class="content"></div>

Padding % and absolute position

If there are any problems with using a 0-height element, the demo also has a green box that's implemented using a wrapper element and absolute position. Not sure if there are any advantages to this approach.

.wrapper {
    position: relative;
    width: 100%;
    padding-bottom: 30%;
}
.wrapper .content {
    position: absolute;
    width: 100%;
    height: 100%;
}
...
<div class="wrapper">
    <div class="content"></div>
</div>
Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
  • wow! I was searching for a solution to my problem and found this perfect solution... 7 years later! To answer your question, I prefer the 2nd solution, specially when dealing with images of different sizes: it's easier to align images when the position is absolute. – Marco May 08 '20 at 17:01
13

This is now possible on modern browsers with vw and vh units:

width: 100vw;
height: 30vw; /* 30% of width */

Browser support: http://caniuse.com/#feat=viewport-units

Yeah!

ndp
  • 21,546
  • 5
  • 36
  • 52
  • +1 for a modern solution. Just keep in mind that vm support is for IE9 and above! (Not including support for vmin and vmax) – calcazar Jan 26 '17 at 16:04
  • 15
    Unfortunately this is based on the size of the viewport, not the size of the parent element. – kojow7 Nov 22 '17 at 21:13
3

Also with JQuery, you could do:

$(window).ready(function () {
    var ratio = 3 / 10, $div = $('#my_proportional_div');
    $div.height($div.width() * ratio);
    $(window).bind('resize', function() { $div.height($div.width() * ratio); });
});

because the Padding % solution suggested doesn't work with max/min-width and max-min height.

sebnukem
  • 8,143
  • 6
  • 38
  • 48