Child elements with margins within DIVs

后端 未结 4 862
轻奢々
轻奢々 2020-12-13 02:19

I need two consecutive div elements (with backgrounds) to be touching seamlessly, one below the other. However, this layout breaks when I put a child p

相关标签:
4条回答
  • 2020-12-13 03:03

    Add overflow: hidden or overflow: auto to the div

    0 讨论(0)
  • 2020-12-13 03:03

    Solution 1

    Add overflow: hidden/auto to the containing div to prevent the margin collapsing.

    Solution 2

    Add positive padding to the containing div and equal negative margin to the inner element

    New Solution

    Add padding of 0.01px to the containing div, this will prevent the margin collapsing but won't need any negative margin on the inner element.

    0 讨论(0)
  • That is the expected behavior*. There are a few ways to get around it. If you float the divs, they will contain the margins of child elements and prevent margin collapsing. Another approach is to add a border or padding to the divs.

    * The margins of the div and the p "combine to form a single margin", even though they are nested, because they have adjoining margins with no padding or border between them.

    0 讨论(0)
  • 2020-12-13 03:10

    Setting a positive padding, and a corresponding negative margin on the div element seems to fix the issue, though I know not why.

    <div style="background: #ccccff">Top Div</div>
    <div style="background: #ffcccc; padding: 1px; margin: -1px"><p>Bottom Div</p></div>
    
    0 讨论(0)
提交回复
热议问题