css系列之clear属性

860 阅读1分钟

先看下面的一个例子:

.one{
    width: 100px;
    height:100px;
    background:yellow;
    float: left;;
 }
 .three{
     width:300px;
     height:300px;
     background:tomato;
     float:right;
  }
 .two{
    width:200px;
    height:200px;
    background:green;
 }
<div class="one">one</div>
<div class="three">three</div>
<div class="two">two</div>

如下图:

由于one盒子的浮动,导致two盒子位置上移,即two盒子受到了one盒子浮动的影响。如果我们不想某个元素因为其他元素的浮动导致位置的改变,我们可以利用clear属性来清除浮动元素对当前元素的影响。

clear属性

作用:可用于清除浮动的影响。
clear属性有三个可选值,left | right | bothleft: 代表可清除左侧浮动元素的影响。
right: 代表可清除右侧浮动元素的影响。
both: 会选择leftright影响最大的来清除浮动。

原理:给当前元素设置了个外边距,使其位置不受浮动元素的影响。
.one{
    width: 100px;
    height:100px;
    background:yellow;
    float: left;
 }
 .three{
     width:300px;
     height:300px;
     background:tomato;
     float:right;
  }
 .two{
    width:200px;
    height:200px;
    background:green;
    clear:left;
 }
<div class="one">one</div>
<div class="three">three</div>
<div class="two">two</div>

clear:left时,浏览器默认的当前元素加了外边距(margin)100px,如下图:

clear:right时,浏览器默认的当前元素加了外边距(margin)300px,如下图:

clear:both时,浏览器默认的当前元素加了外边距(margin)300px,如下图:

clear解决高度塌陷的问题

.parent{
   width:200px;
   border:solid 5px black;
}
.child{
   float:left;
   width:200px;
   height:200px;
   background:green;
}
.parent::after{
   content:"";
   display: table;
   clear: both;
 }
.parent {
  /* 触发 hasLayout */ 
  zoom: 1; // 兼容ie
}
<div class="parent">
  <div class="child">child</div>
</div>