问题描述
我需要两个连续的 div
(具有背景)无缝地接触,一个在另一个之下。但是,当我把一个 p
元素放到底部 div
时, p
元素的边距强制在 div
之间留出空白。这是奇怪的行为,因为我预计 p
的边缘保持在 div
。它在Firefox,Chrome和IE 8上的呈现方式相同。
I need two consecutive div
s (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
s. 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>
以下是它的外观。
我可以通过将 p
元素的边距更改为paddings来修复此问题,但是我还必须这样做与头元素,列表元素,和任何其他元素我想使用在 div
开始。这是不可取的。
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.
有人可以告诉我:我缺少箱子模型的什么警告?是否有一个简单的方法来修复这个问题,最好通过修改 div
?
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
?
推荐答案
这是 * 。有几种方法来解决它。如果浮动div,它们将包含子元素的边距,并防止边缘折叠。另一种方法是向div添加边框或填充。
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.
* div的边距和p组合形成单个边距,即使它们是嵌套,因为它们具有邻接的边距,它们之间没有填充或边框。
* 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.
这篇关于具有DIV内边距的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!