清除浮动
什么是清除浮动?
当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素,在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外面而影响(甚至破坏)布局的现象。这个现象叫浮动溢出,为了防止这个现象的出现而进行的CSS处理,就叫CSS清除浮动。
如何清除浮动?
1.利用clear样式
.textDiv {
color: blue;
border: 2px solid blue;
clear: left;
}
通过上面的样式,.textDiv
告诉浏览器,我的左边不允许有浮动的元素存在,请清除掉我左边的浮动元素。
2. 父元素结束标签之前插入清除浮动的块级元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
<style>
.topDiv {
width: 500px;
border: 2px solid black;
}
.floatDiv {
width: 100px;
height: 100px;
border: 2px dotted red;
color: red;
margin: 4px;
float: left;
}
.bottomDiv {
width: 500px;
height: 100px;
margin: 5px 0;
border: 2px dotted black;
}
.textDiv {
color: blue;
border: 2px solid blue;
}
</style>
</head>
<body>
<div class="topDiv">
<div class="textDiv">
asdasdasdasdassdasasdasdasdasdasdasdasdasd
</div>
<div class="floatDiv">float left</div>
<div style="clear: both;"></div>
</div>
<div class="bottomDiv">asdasdasdasdasdasdasdasdasdasd</div>
</body>
</html>
3. 利用伪元素(clearfix)
.topDiv::after {
content: "";
display: block;
clear: both;
}
4. 利用overflow清除浮动(利用BFC)
.topDiv {
width: 500px;
border: 2px solid black;
overflow: hidden;
}
margin塌陷
什么是margin塌陷?
margin塌陷也叫外边距重叠、margin合并,块的上外边距(margin-top)和下外边距(margin-bottom)有时合并(折叠)为单个边距,其大小为单个边距的最大值(或如果它们相等,则仅为其中一个),这种行为称为边距折叠。
有三种情况会形成外边距重叠
同一层相邻元素之间
<style>
p:nth-child(1){
margin-bottom: 13px;
}
p:nth-child(2){
margin-top: 87px;
}
</style>
<p>下边界范围会...</p>
<p>...会跟这个元素的上边界范围重叠。</p>
没有内容将父元素和后代元素分开
如果没有边框border
,内边距padding
,行内内容,也没有创建块级格式上下文或清除浮动来分开一个块级元素的上边界margin-top
与其内一个或多个后代块级元素的上边界margin-top
;或没有边框,内边距,行内内容,高度height
,最小高度min-height
或 最大高度max-height
来分开一个块级元素的下边界margin-bottom
与其内的一个或多个后代后代块元素的下边界margin-bottom
,则就会出现父块元素和其内后代块元素外边界重叠,重叠部分最终会溢出到父级块元素外面。
空的块级元素
当一个块元素上边界margin-top
直接贴到元素下边界margin-bottom时也会发生边界折叠。这种情况会发生在一个块元素完全没有设定边框border
、内边距padding
、高度height
、最小高度min-height
、最大高度max-height
、内容设定为inline
或是加上clear-fix的时候。
解决margin塌陷
通过触发BFC解决
float
属性为left
/right
overflow
为hidden
/scroll
/auto
position
为absolute
/fixed
display
为inline-block
/table-cell
/table-caption