在开发中,从美工MM给你Html代码中,肯定能经常看<div style="clear:both;"></div>这样的代码,但是你真的能明白它是做什么用的吗?

如:

<div style="border:2px solid red;">

   <div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>

   <div style="clear:both;"></div>

</div>

 

你可以将此部分代码放到一个HTML页面看看效果,然后在去掉<div style="clear:both;"></div>看一下效果,就知道这句话的作用了。

 

如图:

 

1)有clear:both的:

你真的理解clear:both吗?

2)无clear:both

你真的理解clear:both吗?

 

这样看,应该就一目了然了:原来后边的Clear:both;其实就是利用清除浮动来把外层的div撑开,所以有时候,我们在将内部div都设置成浮动之后,就会发现,外层div的背景没有显示,原因就是外层的div没有撑开,太小,所以能看到的背景仅限于一条线。

 

但这种办法就是最好了的吗?

我这么说,当然答案就不是了。可以采用通过Hack实现:

 

<style>

 

 .clearfix:after{

       visibility: hidden;

       display: block;

       font-size: 0;

       content: ".";

       clear: both;

       height: 0;

}

 

   * html .clearfix{zoom: 1;}

   

   *:first-child + html .clearfix{zoom: 1;}

   </style>

<div class="clearfix" style="border: 2px solid red;">

   <div style="float: left; width: 80px; height: 80px; border: 1px solid blue;">

        TEST DIV</div>

</div>

 

看完解决办法,咱们来看里边的原理:

1)、首先是利用:after这个伪类来兼容FFChrome等支持标准的浏览器。

:after伪类IE不支持,它用来和content属性一起使用设置在对象后的内容,例如:

a:after{content:"(link)";}

这个CSS将会让a标签内的文本后边加上link文本文字。

 

2)、利用“* html”这个只有IE6认识的选择符,设置缩放属性“zoom: 1;”实现兼容IE6

3)、利用“*:first-child + html”这个只有IE7认识的选择符,设置缩放属性“zoom: 1;”实现兼容IE7

相关文章:

  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2022-02-15
  • 2021-04-19
  • 2021-08-07
  • 2021-11-19
猜你喜欢
  • 2021-05-17
  • 2021-04-26
  • 2021-06-09
  • 2022-12-23
  • 2021-08-19
  • 2021-09-21
  • 2021-07-15
相关资源
相似解决方案