浮動不是一個正常流布局,浮動元素會從文檔的正常流中刪除,但是他還是會印象布局,浮動應用於所有的元素,當一個元素浮動時,其他內容會“環繞”該元素。
float屬性有四個值:left,right分別浮動元素到相應的方向,none(默認),使元素不浮動,inherit將從父級元素獲取float值
float用處
可用來創建全部網頁布局,如導航條的一行排列,左右兩欄布局 ,浮動在左右兩欄布局中很常見。
例:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style type="text/css"> body{text-align: center} #container{ width:500px; height:auto; margin:auto; } #header{ width:500px; height:100px; background-color: red; } #left{ width:130px; height:300px; background-color: green; float:left; } #right{ width:350px; height:300px; background-color: blue; float:right; } #footer{ width:500px; height:100px; background-color: yellow; /*clear:both;*/ } </style> </head> <body> <div id="container"> <div id="header">header</div> <div id="left">side bar</div> <div id="right">main content</div> <div id="footer">footer</div> </div> </body> </html>
清除浮動之后
浮動造成的塌陷問題
如果父元素只包含浮動元素,那么它的高度就會塌陷為零,如果父元素不包含任何的可見背景,這個問題是很難注意到的。
解決父元素塌陷問題
1、可以為父級元素設置一個height
2、可以為父級元素設置overflow:hidden;
3、可以為父級元素設置一個dislplay:inline-block;
為父級元素設置一個dislplay:inline-block;效果
清除浮動的技巧
如果很明確知道接下來的元素會是什么,則可以使用clear:both;來清除浮動此外還有以下清除方法
1、使用空的div方法
2、利用overflow屬性, 如果父元素的這個屬性設置為 auto 或者 hidden,父元素就會擴展以包含浮動。
3、簡單且較聰明的清除方法(css偽選擇符 :after)來清除浮動,但是需要緊挨着浮動元素
#container:after{
display: block;
content: ' ';
clear:both;
}