<div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> </div>
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;} .div1{ width:80px; height:80px; background:#f00; float:left; } .div2{ width:80px; height:80px; background:blue; float:left; } .div3{ width:80px; height:80px; background:sienna; float:left; }
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;} .div1{ width:80px; height:80px; background:#f00; /*float:left;*/ } .div2{ width:80px; height:80px; background:blue;/* float:left; */} .div3{ width:80px; height:80px; background:sienna;/* float:left;*/ }
<div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> <div class="clear"></div> </div>
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;} .div1{ width:80px; height:80px; background:#f00; float:left; } .div2{ width:80px; height:80px; background:blue; float:left; } .div3{ width:80px; height:80px; background:sienna; float:left; } .clear{ clear:both; height:0; line-height:0; font-size:0; }
方法二:父级div定义 overflow:auto;(主意:是父级div,也就是这里的 div.outer)。
<div class="outer over-flow"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> </div>
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;} .div1{ width:80px; height:80px; background:#f00; float:left; } .div2{ width:80px; height:80px; background:blue; float:left; } .div3{ width:80px; height:80px; background:sienna; float:left; } .over-flow{ overflow:auto; zoom:1; } //zoom:1;是在处理兼容性问题
.outer { zoom:1; } //为了兼容性,因为ie6/7不能使用伪类,所以加上此行代码。 .outer:after { clear:both;content:‘‘;display:block;width:0;height:0;visibility:hidden; }
利用伪元素,就可以不再HTML中加入标签。
:after 的意思是再.outer内部的最后加入为元素:after,
首先要显示伪元素,所以display:block,
然后为伪元素加入空内容,以便伪元素中不会有内容显示在页面中,所以, content:"";
其次,为使伪元素不影响页面布局,将伪元素高度设置为0,所以, height:0,
最后,要清除浮动,所以,clear:both。
原文:http://www.cnblogs.com/zhongjiang/p/6440355.html