添加边框 "pushes down" 内容

Adding a border "pushes down" contents

我有一个 p 元素,在 div 元素中包含一段文本。 div 元素上没有边框,p 元素位于左上角,但是如果我向 div 元素添加边框,它 "pushes down" 从顶部边缘开始的段落(但是不是左边缘)。

为什么会出现这种情况?有什么方法可以防止这种情况发生?

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>

更新:

您可以通过在 p 标签的样式中添加 margin: 0; 来阻止这种移动。请参阅下文,了解发生这种情况的方式和原因。


您的 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. From that question (first part originally quoted from 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; }

这与margin collapse有关。
<p> 元素的边距与其父元素一起折叠。

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... if and only if... no line boxes, no clearance, no padding and no border separate them.


为了防止您的两个示例的边距崩溃,您可以使用 border 以外的方法。例如,overflow:auto:

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.

html,
body {
  height: 100%;
}

div {
  min-width: 300px;
  max-width: 500px;
  min-height: 200px;
  max-height: 450px;
  height: 100%;
  background-color: Pink;
  overflow: auto;
  margin: 0 0 1em;
}

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>

另请参阅:
Mastering margin collapsing.
What You Should Know About Collapsing Margins.