CSS Float(浮動(dòng))
float是什么?
float即為浮動(dòng),在CSS中的作用是使元素脫離正常的文檔流并使其移動(dòng)到其父元素的“最左邊”或“最右邊”。下面解釋下這個(gè)定義中的幾個(gè)名詞的概念:
文檔流:在html中文檔流即為元素從上至下排列的順序。
脫離文檔流:元素從正常的排列順序被抽離。
最左邊/最右邊:上述的移動(dòng)到父元素最左和最右是指元素往左或往右移動(dòng)直到碰到另一個(gè)浮動(dòng)元素或父元素內(nèi)容區(qū)的邊界(不包括padding)。
float屬性:
① left :元素向左浮動(dòng)。
② right :元素向右浮動(dòng)。
③ none :默認(rèn)值。
?、?inherit :從父元素繼承float屬性。
實(shí)例:左浮動(dòng)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>實(shí)例</title> <title>float屬性</title> <style type="text/css"> #a { background-color:Red; height:50px; width:100px; } #b { background-color:Yellow; height:50px; width:200px; float:left; } #c { background-color:Blue; height:50px; width:300px; } #d { background-color:Gray; height:50px; width:400px; } </style> </head> <body> <div id="a">div-a</div> <div id="b">div-b</div> <div id="c">div-c</div> <div id="d">div-d</div> </body> </html>
實(shí)例:右浮動(dòng)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>實(shí)例</title> <title>float屬性</title> <style type="text/css"> #a { background-color:Red; height:50px; width:100px; } #b { background-color:Yellow; height:50px; width:200px; float:right; } #c { background-color:Blue; height:50px; width:300px; } #d { background-color:Gray; height:50px; width:400px; float:right; } </style> </head> <body> <div id="a">div-a</div> <div id="b">div-b</div> <div id="c">div-c</div> <div id="d">div-d</div> </body> </html>
彼此相鄰的浮動(dòng)元素
如果你把幾個(gè)浮動(dòng)的元素放到一起,如果有空間的話,它們將彼此相鄰。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>實(shí)例</title> <title>float屬性</title> <style type="text/css"> #a { background-color:Red; height:50px; width:100px; } #b { background-color:Yellow; height:50px; width:200px; } #c { background-color:Blue; height:50px; width:300px; } #d { background-color:Gray; height:50px; width:400px; } div { float:left; } </style> </head> <body> <div id="a">div-a</div> <div id="b">div-b</div> <div id="c">div-c</div> <div id="d">div-d</div> </body> </html>
清除浮動(dòng) - 使用 clear
元素浮動(dòng)之后,周?chē)脑貢?huì)重新排列,為了避免這種情況,使用 clear 屬性。
clear 屬性指定元素兩側(cè)不能出現(xiàn)浮動(dòng)元素。