0

According to many sources, the height of a div (if given as a percentage) is determined as the percentage of its parent's width. Why is it then that if you resize a window to make it smaller horizontally, the contents of the window don't also get smaller vertically?

Simple page with just a div. http://tuningcode.com/practice/2014-4-24-05.html

Chris Middleton
  • 5,654
  • 5
  • 31
  • 68

2 Answers2

2

This is untrue. This minor gimmick only happens when you try to using percentage-based top/bottom margins and /or paddings. Height is computed as percentage of the containing parent's own calculated height - see example here: http://jsfiddle.net/teddyrised/gB65X/

Let's say we have the markup:

<div>
    <img src="http://placehold.it/500x500" />
</div>

and the following CSS:

body {
    height: 500px;
}
div {
    overflow: hidden;
    height: 75%;
}
div img {
    display: block;
}

<div> will, by default behavior, stretch to the full height of parent (100% = 500px). But since we restrict it's height to 75%, it will have a final computed height of 375px.


Now you set the padding of the <div> to 10%: http://jsfiddle.net/teddyrised/gB65X/1/

You can see that the padding, curiously, are equal along both axis, which should not be the case. If you check your inspector, you can see that the computed padding of top/bottom is identical to that of left/right, even though the height and the width of the wrapping parent, <body>, are not the same.


In fact, this behavior is commonly exploited to create perfectly squared CSS elements without the use of JS: http://jsfiddle.net/teddyrised/gB65X/2/ If we make the following modifications to the original fiddle:

div {
    overflow: hidden;
    padding-bottom: 50%;
    height: 0;
    width: 50%;
}

You can see that <div> has effectively become a flexible/responsible square whose dimensions depends solely on the viewport width, not height ;)

Community
  • 1
  • 1
Terry
  • 63,248
  • 15
  • 96
  • 118
  • @AmadeusDrZaius Sorry, was on mobile. Yeah, missed that word out. Will edit asap! – Terry Apr 24 '14 at 19:02
  • So you're saying that an element doesn't inherit its height as a percentage of its parent's width? Just margin and padding values? EDIT: Nvm, thanks for the link. – Chris Middleton Apr 24 '14 at 19:04
  • Only **percentage-based vertical** margin and padding values will be calculated based on element's own width. – Terry Apr 24 '14 at 19:05
  • 1
    @AmadeusDrZaius Updated answer with two additional fiddles to explain the concept :) – Terry Apr 24 '14 at 19:15
1

From mozillas MDN https://developer.mozilla.org/en-US/docs/Web/CSS/height

height: 75%      /* <percentage> values */

<percentage>
    Specified as a <percentage> of containing block's height.

So your height is relative to the parents height.

I think you might be thinking about padding and margin percentage.

Rúnar Berg
  • 4,229
  • 1
  • 22
  • 38