北京高端网站设计灰色关键词排名代发
一、浮动的副作用
浮动可以让我们灵活的布局,但是也会带来一定的副作用。浮动最常见的副作用有两个:
(1)父元素高度塌陷,从而导致边框不能撑开。
(2)页面布局错乱。
清除浮动,其实就是为了清除元素被定义浮动之后带来的副作用。在CSS中,常见的清除浮动的方法有三种:
(1)clear:both
(2)overflow:hidden
(3)::after伪元素
二、清除浮动的方法
1、clear:both
在CSS中,我们可以使用clear属性来清除浮动。clear属性有三种取值:left、right、both。通常,我们直接使用clear:both来清除所有浮动。
需要注意的是注意:clear属性不是应用于浮动元素本身,而是应用于浮动元素后面的元素。如下例:
...
<head><style>#wrapper{width:200px;border:1px solid black;}#first,#second{width:80px;height:100px;}#first{float:left;border:1px solid red;}#second{float:right;border:1px solid blue;}.clear{clear:both;/*关键代码,清除浮动*/}</style>
</head>
<body><div id="wrapper"><div id="first"></div><div id="second"></div><div class="clear"></div></div>
</body>
其在浏览器中预览效果为:
分析:该方法为了清除元素的浮动,往往会在浮动元素后面添加一个div标签。很多时候这个标签仅仅是为了清除浮动而添加的,没有其他任何意义。虽清除了浮动,但破坏了HTML代码的语义。且如果页面要清除多次浮动,就会添加很多多余的div标签。
2、overflow:hidden
该方法同样可以用于清除浮动,但需要注意的是:overflow:hidden应用于浮动元素的父元素,而非浮动元素本身。看下例:
...
<head><style>#wrapper{overflow:hidden;/*用于清除浮动*/width:200px;border:1px solid black;}#first,#second{width:80px;height:100px;}#first{float:left;border:1px solid red;}#second{float:right;border:1px solid blue;}</style>
</head>
<body><div id="wrapper"><div id="first"></div><div id="second"></div></div>
</body>
其在浏览器中预览效果为:
分析:该方法相对于clear:both方法而言,避免了添加多余的标签,并且不会破坏HTML代码的语义结构。不过,overflow:hidden会隐藏超出父元素的内容部分,有时候这并不是我们想要的效果。
3、::after伪元素
使用clear:both、overflow:hidden来清除浮动都会有弊端。最好的方法是:使用::after伪元素结合clear:both来实现。
语法:
.clearfix{*zoom:1;}
.clearfix::after{clear:both;content:"";display:block;
}
该方法我们推荐定义为公共类,然后进行全局引用,以便减少CSS代码。举个例子:
...
<head><style>.clearfix{*zoom:1;}.clearfix::after{clear:both;content:"";display:block;}#wrapper{width:200px;border:1px solid black;}#first,#second{width:80px;height:100px;}#first{float:left;border:1px solid red;}#second{float:right;border:1px solid blue;}</style>
</head>
<body><div id="wrapper" class="clearfix"><div id="first"></div><div id="second"></div></div>
</body>
其在浏览器中预览效果为:
分析:该方法可以避免上述两个方法所遇到的问题,所以在实践中,我们推荐使用这个方法。