Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overflow:hidden on div tag affects background color

Tags:

html

css

The definition of overflow:hidden states that :

the overflowing content is completely hidden, not accessible to the user.

from: http://quirksmode.org/css/css2/overflow.html

But i am curious about this behavior from my js fiddle: https://jsfiddle.net/gd62qmr3/2/

One thing i noticed is that, it gave color to the margins after setting the overflow to hidden?

<div style="background-color:green;overflow:hidden;">
<p>test</p>
</div>

I wanna know why did such behavior occur? the exact block element will have the green background color if there is no overflow but putting overflow will give background color to its margins.

like image 272
Carlos Miguel Colanta Avatar asked Dec 04 '25 11:12

Carlos Miguel Colanta


1 Answers

That's because overflow: hidden affects margin collapse.

p elements have some vertical margin by default. According to the spec, it collapses with the margin of the parent div:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Adjoining vertical margins collapse, except [... not relevant]

[... The] top margin of a box and top margin of its first in-flow child [are adjoining]

enter image description here

However, overflow: hidden prevents that:

Margins of elements that establish new block formatting contexts (such as floats and elements with overflow other than visible) do not collapse with their in-flow children.

enter image description here

like image 194
Oriol Avatar answered Dec 07 '25 01:12

Oriol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!