因为浮动框不在普通的文档流中,所以它不占据空间。如下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| .container { background: gray; } .content { width: 100px; height: 100px; background: blue; float: left; } .sidebar { width: 100px; height: 100px; background: green; float: right; }
|
1 2 3 4
| <div class="container"> <div class="content"></div> <div class="sidebar"></div> </div>
|
但是因为浮动元素脱离了文档流,所以.container不占据空间。
方法一:添加空标签
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| .container { background: gray; } .content { width: 100px; height: 100px; background: blue; float: left; } .sidebar { width: 100px; height: 100px; background: green; float: right; } .clear { clear: both; }
|
1 2 3 4 5 6
| <div class="container"> <div class="content"></div> <div class="sidebar"></div> <div class="clear"></div> </div>
|
但是这个方式的弊端是添加了无意义的标签;
如果有很多地方要清除浮动,那么将会出现大量的无意义的标签。
方法二:使用overflow属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| .container { background: gray; overflow: auto; zoom:1; } .content { width: 100px; height: 100px; background: blue; float: left; } .sidebar { width: 100px; height: 100px; background: green; float: right; }
|
1 2 3 4
| <div class="container"> <div class="content"></div> <div class="sidebar"></div> </div>
|
overflow属性有一个有用的副作用,这会自动清理包含的任何浮动元素;
不过使用overflow的时候,可能会对页面表现带来影响,而且这种影响是不确定的,你最好是能在多个浏览器上测试你的页面;
方法三:使用:after伪类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| .container { background: gray; } .content { width: 100px; height: 100px; background: blue; float: left; } .sidebar { width: 100px; height: 100px; background: green; float: right; } .clear:after { content: "."; height: 0; visibility: hidden; display: block; clear: both; }
|
1 2 3 4
| <div class="container clear"> <div class="content"></div> <div class="sidebar"></div> </div>
|
这个方法在大多数现代浏览器中都是有效的,淘宝首页也用了这种方式来清除浮动,但是在IE6和更低版本中不起作用,IE6下需要hack。
但奇怪的是Windows中的Internet Explorer 6及以下版本并不支持CSS 2.1中的after伪类而Mac中的Internet Explorer却可以正常使用,所以我们还要单独针对Win/IE进行处理。在区分Win和Mac中Internet Explorer的诸多方法中,最常用就是Holly招数。Holly招数的原理是这样的,CSS代码
1 2 3 4 5 6 7 8
| * html .container{ height:1%; } .container { display:block; }
|
上面的代码中有两行注释,其中第一行结束时出现了反斜杠(\),在Mac的Internet Explorer中会认为注释并没有结束,于是继续向下直到第一个完事的“*/”出现,这中间的所有字符都被当作是注释,而IE/Win却也只会把第一行和第三行看作是注释,中间的为有效代码。所以这样就区分出来了不同平台上的IE了。
See the Pen :after clear float by Wing (@winguno) on CodePen.
参考:http://www.cnblogs.com/houyulei/archive/2011/12/16/2290229.html