我有一个 p 元素,在 div 元素中包含一段文本。 div 元素上没有边框,p 元素位于左上角,但如果我向 div 元素添加边框,它会从顶部边缘(但不是左边缘)“下推”段落。
为什么会发生这种情况?有什么方法可以防止这种情况发生?
html,
body {
height: 100%;
}
div {
min-width: 300px;
max-width: 500px;
min-height: 200px;
max-height: 450px;
height: 100%;
background-color: Pink;
}
div.first {
border-width: 2px;
border-style: solid;
border-color: Black;
}
p {
width: 75%;
height: 75%;
background-color: Black;
color: White;
}
<div class="first">
<p class="one">Paragraph one text...</p>
</div>
<div class="second">
<p class="two">Paragraph two text...</p>
</div>
更新:
您可以通过将 margin: 0;
添加到您的 p
标记的样式中来阻止此移动。请参阅下文,了解发生这种情况的方式和原因。
p
标签被下推的原因是边距折叠(或者更确切地说,当您设置边框时边距不折叠)。
See this page for a more in-depth explanation of how it works .从该页面:
The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.
基本上,您的边距会被浏览器折叠 当您没有设置边框时,但它们是经过计算的 当你设置边框时。
有关防止浏览器折叠边距的方法,see this question .从那个问题(第一部分最初引用自 this other question ):
Found an alternative at Child elements with margins within DIVs You can also add:
.parent { overflow: auto; }
or:
.parent { overflow: hidden; }
This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:
.parent {
padding-top: 1px;
margin-top: -1px;
}