您的位置:首页 > Web前端 > HTML

使用伪元素(:after)清除浮动元素

2015-01-05 12:17 756 查看
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>清除浮动元素</title>
<style>
* {margin:0; padding:0; border:0;}
#div1 {width:100%; height:auto; background-color:#F00; float:left;}
#div2 {width:800px; margin:auto; background-color:#00F; margin-top:50px;}
#div3 {width:100px; height:100px; background-color:#0F0; float:left; margin-left:150px;margin-top:150px; margin-bottom:100px;}
#div2:after {display:block; height:0; content:""; clear:both;}
</style>
</head>

<body>
<div id="div1">
<div id="div2">
<div id="div3"></div>
</div>
</div>
</body>
</html>

#div1浮动,#div2不浮动,#div3浮动

如果不清除#div3的浮动,#div1可以包含#div3,但是,#div2的高度会为0px,就不能包含#div3。

一种方法是在#div2内部,#div3后面,加入类似这样一段代码“<div style="clear:both"></div>"。

利用伪元素,就可以不再HTML中加入标签。

如上面CSS代码,#div2:after {display:block; height:0; content:""; height:0; clear:both;}

#div2:after 的意思是再#div2内部的最后加入为元素:after,

首先要显示伪元素,所以display:block,

然后为伪元素加入空内容,以便伪元素中不会有内容显示在页面中,所以, content:"",

其次,为使伪元素不影响页面布局,将伪元素高度设置为0,所以, height:0,

最后,要清除#div3,所以,clear:both。

最后的显示效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  html float after 伪元素