標籤:
分析HTML代碼結構:
div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div></div>
分析CSS代碼樣式:
.outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px;}.div1{width: 80px;height: 80px;background: red;float: left;}.div2{width: 80px;height: 80px;background: blue;float: left;}.div3{width: 80px;height: 80px;background: sienna;float: left;}
這裡我沒有給最外層的DIV.outer 設定高度,但是我們知道如果它裡面的元素不浮動的話,那麼這個外層的高是會自動被撐開的。但是當內層元素浮動後,就出現了一下影響:
(1):背景不能顯示 (2):邊框不能撐開 (3):margin 設定值不能正確顯示
二、清楚css浮動:
方法一:添加新的元素 、應用 clear:both;
HTML:
<div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> <div class="clear"></div></div>
CSS:
.clear{clear:both; height: 0; line-height: 0; font-size: 0}
方法二:父級div定義 overflow: auto(注意:是父級div也就是這裡的 div.outer)
HTML:
<div class="outer over-flow"> //這裡添加了一個class <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> <!--<div class="clear"></div>--></div>
CSS:
.over-flow{ overflow: auto; zoom: 1; //zoom: 1; 是在處理相容性問題}
原理:使用overflow屬性來清除浮動有一點需要注意,overflow屬性共有三個屬性值:hidden,auto,visible。我們可以使用hiddent和auto值來清除浮動,但切記不能使用visible值,如果使用這個值將無法達到清除浮動效果,其他兩個值都可以,其區據說在於一個對seo比較友好,另個hidden對seo不是太友好,其他區別我就說不上了,也不浪費時間。
方法三: 據說是最高大上的方法 :after 方法:(注意:作用於浮動元素的父親)
先說原理:這種方法清除浮動是現在網上最拉風的一種清除浮動,他就是利用:after和:before來在元素內部插入兩個元素塊,從面達到清除浮動的效果。其實現原理類似於clear:both方法,只是區別在於:clear在html插入一個div.clear標籤,而outer利用其偽類clear:after在元素內部增加一個類似於div.clear的效果。下面來看看其具體的使用方法:
.clearfix:after,.clearfix:before {display: block;content: ".";height: 0;line-height: 0;overflow: hidden;visibility: none;clear: both;}.clearfix {zoom:1; /*相容ie7一下*/}
css的清除浮動