当容器未设置高度,且容器的内容中有浮动(float为left或right)的元素,在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外面而影响(甚至破坏)布局的现象。这个现象叫浮动溢出,为了防止这个现象的出现而进行的CSS处理,就叫CSS清除浮动。
clear:both 相当于专门设置了一个空盒子来撑起父元素的高度
-
- .father {
- background-color: pink;
- border: solid 1px black;
- width: 200px;
- }
-
- .son1{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: blue;
- float: left;
- }
- .son2{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: yellow;
- float: left;
- }
- .son3{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: green;
- float: left;
- }
-
- .clear {
- clear:both;
- }
-
- <div class="father">
- <div class="son1">div>
- <div class="son2">div>
- <div class="son3">div>
- <div class="clear">div>
- div>
给有浮动元素的container添加overflow:hidden或者overflow:auto;可以清除浮动
- .father {
- background-color: pink;
- border: solid 1px black;
- width: 200px;
- overflow: auto;
- }
-
- .son1{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: blue;
- float: left;
- }
- .son2{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: yellow;
- float: left;
- }
- .son3{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: green;
- float: left;
- }
-
- <div class="father">
- <div class="son1">div>
- <div class="son2">div>
- <div class="son3">div>
- div>
给浮动元素的容器添加一个clearfix的class,然后给这个class添加一个:after伪元素实现元素末尾添加一个看不见的块元素(Block element)清理浮动,通过清除伪元素的浮动,达到撑起父元素高度的目的。该伪元素的display值为block(也可以使用table,因为table也是一个块级元素)。
- .father {
- background-color: pink;
- border: solid 1px black;
- width: 200px;
- }
-
- .son1{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: blue;
- float: left;
- }
- .son2{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: yellow;
- float: left;
- }
- .son3{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: green;
- float: left;
- }
-
- .clearfix::after{
- clear: both;
- display: block;
- content: "";
- }
-
- .clearfix {
- *zoom: 1;
- }
-
- <div class="father clearfix">
- <div class="son1">div>
- <div class="son2">div>
- <div class="son3">div>
- div>
clearfix::before,clearfix::after
- .father {
- background-color: pink;
- border: solid 1px black;
- width: 200px;
- }
-
- .son1{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: blue;
- float: left;
- }
- .son2{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: yellow;
- float: left;
- }
- .son3{
- width: 50px;
- height: 50px;
- border: solid 1px black;
- background-color: green;
- float: left;
- }
-
- .clearfix{
- *zoom: 1;
- }
-
- .clearfix::before,.clearfix::after{
- content: '';
- display: block;
- clear: both;
- }
-
- <div class="father clearfix">
- <div class="son1">div>
- <div class="son2">div>
- <div class="son3">div>
- div>