<section> <img src="images/rubber_duck.jpg"> <p>It's fun to float.</p> </section> <footer>Here is the footer element that runs across the bottom of the page.</footer>
这是一张带标题的图片,图片和标签包含在一个section元素,section后面紧跟着一个footer元素。
接下来是CSS代码:浏览器
section{border:1px solid blue; margin: 0 0 10px 0;} img{float:left;} footer{border:1px solid red;}
能够想象,浮动图片后标题跑到了右边,section也收缩到只包含文本的高度,footer也跑到了上面,紧挨着section。为了使section包住浮动元素,有如下方法。code
overflow:hidden
section{border:1px solid blue; float:left; width:100%;} img{float:left;} footer{border:1px solid red; clear:left;}
浮动section之后,无论其子元素是否浮动,它都会牢牢地包围(收缩包裹)住它的子元素,所以,须要用width:100%
再让section与浏览器同宽。另外,因为section也浮动了,为了强制让footer在section下方,要给它应用clear:left
。图片
添加一个非浮动的子元素,而后清除它。因为包含元素必定会包围非浮动元素,并且清除会让这个子元素位于浮动元素的下方,所以包含元素必定会包含这个子元素以及前面的浮动元素。方法有两种。element
第一种:it
<section> <img src="images/rubber_duck.jpg"> <p>It's fun to float.</p> <div class="clear_me"></div> </section> <footer>Here is the footer element that runs ...</footer>
CSS:io
section{border:1px solid blue;} img{float:left;} .clear_me{clear:left} footer{border:1px solid red;}
第二种:class
第一种添加一个纯表现性元素不太好,能够添加一个用CSS来添加这个清除元素的方法。float
<section class="clearfix"> <img src="images/rubber_duck.jpg"> <p>It's fun to float.</p> </section> <footer>Here is the footer element that runs ...</footer> .cleatfix:after{ content:"."; display:block; height:0; visbility:hidden; clear:both; }
以上三种方法的使用要因地制宜,好比,不能在下拉菜单的顶级元素使用overflow:hidden
;不能对已经靠自动外边距居中的元素使用“浮动父元素”技术。方法