什麼是浮動float

浮動不是一個正常流佈局,浮動元素會從文檔的正常流中刪除,可是他仍是會印象佈局,浮動應用於全部的元素,當一個元素浮動時,其餘內容會「環繞」該元素。css

float屬性有四個值:left,right分別浮動元素到相應的方向,none(默認),使元素不浮動,inherit將從父級元素獲取float值html

float用處ide

可用來建立所有網頁佈局,如導航條的一行排列,左右兩欄佈局 ,浮動在左右兩欄佈局中很常見。佈局

例:spa

 

<!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>

 

清除浮動以後code

浮動形成的塌陷問題htm

若是父元素只包含浮動元素,那麼它的高度就會塌陷爲零,若是父元素不包含任何的可見背景,這個問題是很難注意到的。blog

解決父元素塌陷問題文檔

一、能夠爲父級元素設置一個heightit

二、能夠爲父級元素設置overflow:hidden;

三、能夠爲父級元素設置一個dislplay:inline-block;

爲父級元素設置一個dislplay:inline-block;效果

清除浮動的技巧

 若是很明確知道接下來的元素會是什麼,則能夠使用clear:both;來清除浮動此外還有如下清除方法

一、使用空的div方法

二、利用overflow屬性, 若是父元素的這個屬性設置爲 auto 或者 hidden,父元素就會擴展以包含浮動。

三、簡單且較聰明的清除方法(css僞選擇符 :after)來清除浮動,可是須要緊挨着浮動元素

    #container:after{
            display: block;
            content: ' ';
            clear:both;
        }
相關文章
相關標籤/搜索