1,css
1.1,margin没有合并
1.1.1,遇到问题
一直都知道垂直方向上,可能会发生 margin
合并的问题,但后来发现是有前提的。
前提:发生合并的2个元素,必须都是块级元素。
其中一个是内联(
inline
或inline-block
)元素,就不会进行合并!
所以,下面的组合,就不会发生合并
<input type="text" class="brother-input">
<div class="brother-div"></div>
.brother-input {
margin-bottom: 20px;
}
.brother-div {
width: 100px;
height: 50px;
background-color: salmon;
margin-top: 5px;
}
1.1.2,问题扩展
1,除了常见了相邻兄弟元素,父子级元素之外,还有一个会发生合并的情况。
空块级元素的 margin
合并:
<div class="wrapper">
<div class="inner"></div>
</div>
.wrapper {
overflow: hidden;
}
.inner {
margin: 10px 0;
}
此时,外层 div 的高度是 10px ,因为内层这个空的块级元素的 margin-top
和 margin-bottom
发生了合并。
2,即便不是相邻的兄弟元素,也可能发生合并。
<p>第1个p标签</p>
<div></div>
<p>第2个p标签</p>
p {
margin: 10px 0;
}
此时,2个 p 标签之间的距离还是 10px,因为中间的 div 是一个空的块级元素,原本就是会发生合并的元素。
而其实发生了3次合并:
-
第1个 p 标签的
margin-bottom
和 div 的margin-top
发生了合并, -
第2个 p 标签的
margin-top
和 div 的margin-bottom
发生了合并, -
div 这个空的块级元素,
margin-top
和margin-bottom
发生了合并。
解决:
- 空的 div 设置
border-top
或border-bottom
- 空的 div 设置
padding-top
或padding-bottom
- 空的 div 设置
height
,或是div元素内有内容让其height
不为 0。
1.1.3,父子元素,阻止合并
对于 margin-top
合并( margin-bottom
同理)
- 父元素设置为块状格式化上下文元素。最简单的方法
overflow: hidden
- 父元素设置
border-top
- 父元素设置
padding-top
- 父元素和第一个子元素之间添加
inline-block
元素进行分割。一般用伪元素content: ''; display:inline-block;
进行处理。