技術(shù)分享 調(diào)用clear:both清除浮動
本文和大家重點討論一下clear:both清除浮動的使用,在CSS中我們會經(jīng)常要用到“清除浮動”Clear,比較典型的就是clear:both;該屬性的值指出了不允許有浮動對象的邊。這個屬性是用來控制float屬性在文檔流的物理位置的。
用clear:both清除浮動
在CSS中我們會經(jīng)常要用到“清除浮動”Clear,比較典型的就是clear:both;
CSS手冊上是這樣說明的:該屬性的值指出了不允許有浮動對象的邊。這個屬性是用來控制float屬性在文檔流的物理位置的。
◆當(dāng)屬性設(shè)置float(浮動)時,其所在的物理位置已經(jīng)脫離文檔流了,但是大多時候我們希望文檔流能識別float(浮動),或者是希望float(浮動)后面的元素不被float(浮動)所影響,這個時候我們就需要用clear:both;來清除。
viewplaincopytoclipboardprint?
- <pstylepstyle="float:left;width:200px;">這個是第1列,p>
- <pstylepstyle="float:left;width:400px;">這個是第2列,p>
- <p>這個是第3列。p>
- <pstylepstyle="float:left;width:200px;">這個是第1列,p>
- <pstylepstyle="float:left;width:400px;">這個是第2列,p>
- <p>這個是第3列。p>
如果不用清除浮動,那么第3列文字就會和第1、2列文字在一起,所以我們在第3個這列加一個清除浮動clear:both;
通常,我們往往會將“清除浮動”單獨定義一個CSS樣式,如:
viewplaincopytoclipboardprint?
- .clear{
- clear:both;
- }
- .clear{
- clear:both;
- }
然后使用
◆clear:both;可以終結(jié)在出現(xiàn)他之前的浮動
viewplaincopytoclipboardprint?
- .demodiv{float:left;width:100px;height:50px;
- background:red;margin:5px;}
- .d{clear:both}
- style>
- <divclassdivclass="demodiv">1div>
- <divclassdivclass="demodiv">2div>
- <divclassdivclass="d">div>
- <divclassdivclass="demodiv">3div>
- <divclassdivclass="demodiv">4div>
- .demodiv{float:left;width:100px;height:50px;
- background:red;margin:5px;}
- .d{clear:both}
- style>
- <divclassdivclass="demodiv">1div>
- <divclassdivclass="demodiv">2div>
- <divclassdivclass="d">div>
- <divclassdivclass="demodiv">3div>
- <divclassdivclass="demodiv">4div>
效果圖如下:
#p#
clear:both參數(shù)說明
◆語法:clear:none|left|right|both
◆參數(shù):
none:允許兩邊都可以有浮動對象
both:不允許有浮動對象
left:不允許左邊有浮動對象
right:不允許右邊有浮動對象
◆說明:該屬性的值指出了不允許有浮動對象的邊。請參閱float屬性。對應(yīng)的腳本特性為clear
主要是用在div套div的結(jié)構(gòu)中。如果內(nèi)div是浮動的,一般都需要clear浮動,不然的話內(nèi)div會超出外div的框架
所用什么時候用clear:both;就很重要,一般我們在需要清除浮動的時候用到clear:both;不要輕意用到clear:both;因為它也有副伯用.
你在要浮動的兩個div后再加一個div,并設(shè)置樣式為clear:both,這樣就可以了(因為clear:both說明這個div不允許左右有浮動元素,于是就往下跑,撐開了父div),如下:
viewplaincopytoclipboardprint?
- <divstyledivstyle="float:left;...">
- abc
- div>
- <divstyledivstyle="float:left;...">
- abc
- div>
- <divstyledivstyle="clear:both">div>
- <divstyledivstyle="float:left;...">
- abc
- div>
- <divstyledivstyle="float:left;...">
- abc
- div>
- <divstyledivstyle="clear:both">div>
你這種兩列的情況,我一般都是兩個都float:left。
【編輯推薦】
- ***實現(xiàn)CSS頁面居中方法揭秘
- 八個困擾新手的DIV CSS網(wǎng)頁布局問題
- 全面解析CSS優(yōu)先級規(guī)則
- 專家推薦 10款優(yōu)秀CSS框架
- 實例解析清除CSS float浮動的三種方法