Child elements with margins within DIVs

2019-01-21 19:48发布

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 element into the bottom div. The margins of the p element force a blank gap between both div elements. This is strange behavior, as I am expecting the margin of the p to stay within the content and background area of the div. It renders the same way on Firefox, Chrome and IE 8.

<div style="background: #ccccff">Top Div</div>
<div style="background: #ffcccc"><p>Bottom Div</p></div>

Here's what it looks like.

Image showing the top div (in blue), then a white gap, then the bottom div (in pink). The white gap should not be present.

I could fix this by changing the margins to paddings for the p element, but then I would also have to do this with header elements, list elements, and any other element I want to use at the start of a div. That is not desirable.

Could someone enlighten me: what caveat of the box model am I missing? Is there an easy way to fix this, preferably by modifying the style of the div?

标签: html css xhtml
4条回答
可以哭但决不认输i
2楼-- · 2019-01-21 20:17

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.

查看更多
forever°为你锁心
3楼-- · 2019-01-21 20:19

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>
查看更多
我只想做你的唯一
4楼-- · 2019-01-21 20:29

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.

查看更多
我命由我不由天
5楼-- · 2019-01-21 20:30

Add overflow: hidden or overflow: auto to the div

查看更多
登录 后发表回答