html - 添加边框 "pushes down"内容

标签 html css border

我有一个 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; }

关于html - 添加边框 "pushes down"内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48938043/

相关文章:

java - 通过 Java 从 Javascript 更改填充多个 HTML 语句

php - 一起使用 HTML 和 Php?

border - 如何只删除框阴影的顶部?

css - 转换后 Firefox 边框搞砸了

html - 像模态一样显示的 Div

javascript - Javascript 代码竖起大拇指

javascript - 选择多个按钮时如何允许多个输入

javascript - 带有 id 的 div 不接受任何事件处理程序 JavaScript。没有Jquery

html - Flexbox 模式 1/3/3 列和行组合

CSS 不能过渡 border-style 吗?