Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overflow: hidden on div and body, different behavior

Tags:

html

css

overflow

Given this html:

<body>
  <div id="a"></div>
  <div id="b"></div>
</body>

I want #b to fill all the remaining vertical space of its container block, I began with this:

body {
  height: 500px;
  width: 500px;
  overflow: hidden;
}

#a {
  height: 100px;
  width: 100px;
}

#b {
  height: 100%;
  width: 100%;
}

So #b is 100% height, which means that it is taking the height of its parent container block, which is 500px, the problem is that the overflow: hidden; seems to not work, #b is not clipped.

On the other hand, if I wrap #a and #b with another div with the same properties as body above I have the desired result:

#wrap {
  height: 500px;
  width: 500px;
  overflow: hidden;
}

#a {
  height: 100px;
  width: 100px;
}

#b {
  height: 100%;
  width: 100%;
}

with this html of course:

<body>
<div id="wrap">
<div id="a"></div>
<div id="b"></div>
</div>
</body>

My question is why div and body seems to have different behaviors with the same properties? and is there any way to get the same effect without the wrapper?

To illustrate the question I have created two jsFiddles:

jsFiddle with body tag as wrapper: http://jsfiddle.net/3AMtG/

jsFiddle with div tag as wrapper: http://jsfiddle.net/2QWn3/

Two jsFiddles with the same properties yield different results. Why is that?

like image 282
angvillar Avatar asked Mar 17 '13 14:03

angvillar


1 Answers

The overflow property has certain special behaviors specific to HTML's html and body elements, which are described in the CSS2.1 spec. These special cases are in place to accommodate changing overflow settings on the entire page in normal circumstances so authors simply need to set it on either html or body, but not both.

In this case, when you apply overflow: hidden to body, it actually affects the viewport instead of body (you can see this by resizing the preview pane to make it shorter — no scrollbars will appear on the preview pane itself). This causes #b to overflow the body normally even though you give it a fixed height that's less than the sum of #a and #b. In other words, it's as though you never set it on the body in the first place.

If you set overflow to something other than visible on html, though, this causes the viewport to use the value given to html instead of body, thereby leaving the declaration on body unaffected and allowing it to behave the same way as the wrapper:

html {
  overflow: auto;
}

body {
  height: 500px;
  width: 500px;
  overflow: hidden;
}

jsFiddle preview

like image 60
BoltClock Avatar answered Sep 20 '22 13:09

BoltClock