为什么这些边距重叠?

时间:2017-02-17 03:55:10

标签: html css

在以下代码段中,为什么h2p页边距重叠,但pbutton页边距不重叠?

我已经为背景着色,所以你可以清楚地看到间距是关闭的,即使所有3个元素具有相同的边距....

body {
  position: relative;
  width: 100vw;
  height: 100vh;
}

#textContainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

#textContainer>* {
  position: relative;
  margin: 15px 0;
  background-color: blue;
  color: #fff;
}

button {
  background-color: transparent;
  border: 2px solid rgb(51, 51, 51);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div id="textContainer" class="col-xs-6">
  <h2>Lorem ipsum</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc con non. Proin ut lacus sodales, rutrum mi vel, faucibus lacus. </p>
  <button type="button" class="btn btn-default btn-lg">faucibus lacus</button>
</div>

2 个答案:

答案 0 :(得分:5)

如框模型规范所述,inline-block元素的边距不会崩溃:

  

8 Box model - 8.3.1 Collapsing margins

     

内联块方框的边距不会崩溃(即使是流入的子节点也不会崩溃)。

默认情况下,button元素的displayinline-block,这意味着默认情况下边距不会折叠。

如果您将display元素的button更改为block之类的值,则边距将按预期折叠:

&#13;
&#13;
body {
  position: relative;
  width: 100vw;
  height: 100vh;
}

#textContainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

#textContainer>* {
  position: relative;
  margin: 15px 0;
  background-color: blue;
  color: #fff;
}

button.btn {
  display: block;
  background-color: transparent;
  border: 2px solid rgb(51, 51, 51);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div id="textContainer" class="col-xs-6">
  <h2>Lorem ipsum</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc con non. Proin ut lacus sodales, rutrum mi vel, faucibus lacus. </p>
  <button type="button" class="btn btn-default btn-lg">faucibus lacus</button>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

因为h2,p块元素和button - 内联块元素。对于内联块元素,边距不重叠