在以下代码段中,为什么h2
和p
页边距重叠,但p
和button
页边距不重叠?
我已经为背景着色,所以你可以清楚地看到间距是关闭的,即使所有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>
答案 0 :(得分:5)
如框模型规范所述,inline-block
元素的边距不会崩溃:
8 Box model - 8.3.1 Collapsing margins
内联块方框的边距不会崩溃(即使是流入的子节点也不会崩溃)。
默认情况下,button
元素的display
为inline-block
,这意味着默认情况下边距不会折叠。
如果您将display
元素的button
更改为block
之类的值,则边距将按预期折叠:
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;
答案 1 :(得分:2)
因为h2,p
块元素和button
- 内联块元素。对于内联块元素,边距不重叠