overflow:hidden on div tag affects background color

后端 未结 2 642
时光取名叫无心
时光取名叫无心 2021-01-21 01:40

The definition of overflow:hidden states that :

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

from: http://

相关标签:
2条回答
  • 2021-01-21 02:05

    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]

    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.

    0 讨论(0)
  • 2021-01-21 02:29

    Your color is set to the parent of your paragraph. You have nothing stopping the height of your parent div to expand as far as it wants, so the paragraph margins are making the parent height larger.

    If you were to give a set height to your parent (18px or so) then it will hide the margins (and text technically)

    div {
        height:18px;
    }
    

    https://jsfiddle.net/gd62qmr3/3/

    If you were to set the color to your paragraph, then you will not see the background color in the margins

    div {
        overflow:hidden;
    }
    div p {
        background-color:green;
        margin:20px 0;
    }
    

    https://jsfiddle.net/gd62qmr3/4/

    0 讨论(0)
提交回复
热议问题