圍住浮動元素的三種方法

<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;不能對已經靠自動外邊距居中的元素使用「浮動父元素」技術。方法

相關文章
相關標籤/搜索