如何清除浮动?

156 阅读1分钟

什么事浮动?

  • 在非IE浏览器(如Firefox)下;
  • 当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素;
  • 在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外面而影响(甚至破坏)布局的现象。这个现象叫浮动溢出;
  • 为了防止这个现象的出现而进行的CSS处理,就叫CSS清除浮动。

清除浮动的方法?

方法一:使用clear属性的空元素

在浮动元素后使用一个空元素如<div class="clear"></div>,并在CSS中赋予.clear{clear:both;}属性即可清理浮动。亦可使用<br class="clear" />或<hr class="clear" />来进行清理。

.news {
  background-color: gray;
  border: solid 1px black;
  }

.news img {
  float: left;
  }

.news p {
  float: right;
  }

.clear {
  clear: both;
  }

<div class="news">
<img src="news-pic.jpg" />
<p>some text</p>
<div class="clear"></div>
</div>

方法二

给浮动元素的容器,也就是父元素添加overflow:hidden;overflow:auto;可以清除浮动,

.news {
  background-color: gray;
  border: solid 1px black;
  overflow: hidden;
  *zoom: 1;
  }

.news img {
  float: left;
  }

.news p {
  float: right;
  }

<div class="news">
<img src="news-pic.jpg" />
<p>some text</p>
</div>

方法三:给父元素加上.clearfix

.news {
  background-color: gray;
  border: solid 1px black;
  }

.news img {
  float: left;
  }

.news p {
  float: right;
  }

.clearfix:after{
  content: ''; 
  display: block; 
  clear: both; 
  }

.clearfix {
  /* 触发 hasLayout */ 
  zoom: 1; 
  }

<div class="news clearfix">
<img src="news-pic.jpg" />
<p>some text</p>
</div>