Christopher Christopher - 1 month ago 4
HTML Question

Why is content visible when "overflow" is set to "hidden"?

I'm trying to get a better understanding of the CSS "overflow" property. In the following example I see

overflow:hidden;
but the gray background is visible and reaching to the full 300% of the
div
width.

http://jsfiddle.net/emeRJ/3/

If the overflow is "hidden" I would expect the background to be clipped, not visible. If I change it to "visible" the gray background disappears entirely. I'm confused by this and hope to get a solid understanding of it.

Can someone describe what is happening with the two options?
Which element is actually "overflowing"?

I found the above example from a previous question Properties on CSS overflow


If you have an element that has overflow set to something different
than "visible", the height of the element will be expand according to
the float elements inside.


I gather in this case the width of the element is expanding. However, semantically it makes no sense. If an object is "visible" I expect it to be visible, not hidden, and vice-versa.

Answer

In your example there is no overflow, and thus overflow: hidden is not much relevant other than establishing a block formatting context.

Establishing a block formatting context is just a side-effect which makes the container wrap the floating contents as explained in Floating elements within a div, floats outside of div. Why?

You would see the clipping if the container were narrower than the contents. You can play with the following snippet:

.box {
  width: 200px;
  overflow: hidden;
  background-color: #c3c3c3;
  clear: left;
}
.sub_box {
  float: left;
  width: 400px;
  height: 100px;
  border: 1px solid black;
}
input {
  float: left;
  clear: left;
}
label {
  float: left;
}
#overflow-visible:checked ~ .box { overflow: visible; }
#overflow-visible-bfc:checked ~ .box { overflow: visible; float: left; }
#overflow-hidden:checked ~ .box { overflow: hidden; }
#overflow-scroll:checked ~ .box { overflow: scroll; }
#overflow-auto:checked ~ .box { overflow: auto; }
<input type="radio" name="overflow" id="overflow-visible" checked />
<label for="overflow-visible"><code>overflow: visible</code></label>
<input type="radio" name="overflow" id="overflow-visible-bfc" />
<label for="overflow-visible-bfc"><code>overflow: visible</code> + BFC</label>
<input type="radio" name="overflow" id="overflow-hidden" />
<label for="overflow-hidden"><code>overflow: hidden</code> (BFC)</label>
<input type="radio" name="overflow" id="overflow-scroll" />
<label for="overflow-scroll"><code>overflow: scroll</code> (BFC)</label>
<input type="radio" name="overflow" id="overflow-auto" />
<label for="overflow-auto"><code>overflow: auto</code> (BFC)</label>
<div class="box">
  <div class="sub_box"></div>
  <div class="sub_box"></div>
</div>