close

在進行浮動佈局時,大多數人都深知,在必要的地方進行浮動清理:<div style="clear:both;"></div>。

程序代碼 程式碼
<div style="background:#666;">

  <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
</div>


此時預覽此代碼,我們會發現最外層的父元素float container,並沒有顯示。這是因為子元素因進行了浮動,而脫離了文檔流,導致父元素的height為零。
若將代碼修改為:

程序代碼 程式碼
<div style="background:#666;">
  
  <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
  <div style="clear:both"></div>
</div>


注意,多了一段清理浮動的代碼。這是一種好的CSS代碼習慣,但是這種方法增加了無用的元素。這裡有一種更好的方法,將HTML代碼修改為:

程序代碼 程序代碼
<div  class="clearfix" style="background:#666;">
  
  <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
</div>


定義CSS類,進行「浮動清理」的控制:

程序代碼 程序代碼
.clearfix:after {}{
  content: ".";
  clear: both;
  height: 0;
  visibility: hidden;
  display: block;
}            /* 這是對Firefox進行的處理,因為Firefox支持生成元素,而IE所有版本都不支持生成元素 */
.clearfix {}{
  display: inline-block;    
}                /* 這是對 Mac 上的IE瀏覽器進行的處理 */
/**//* Hides from IE-mac \*/
* html .clearfix {}{height: 1%;}        /* 這是對 win 上的IE瀏覽器進行的處理 */
.clearfix {}{display: block;}        /* 這是對display: inline-block;進行的修改,重置為區塊元素*/
/**//* End hide from IE-mac */    


此時,預覽以上代碼(  刪去這種註釋   ),會發現即使子元素進行了浮動,父元素float container仍然會將其包圍,進行高度自適應。

代碼參考:點這裡...

clear 元素的margin-top被重置為零,當你使用clear(left & both & right)清理一個浮動元素時,該元素的margin-top會被重置為0。所以為了創建浮動列,並使用footer進行浮動清理時,必須對浮動列 (sidebar && content)都指定margin-bottom,最好margin-bottom相同。(Firefox會將margin-top重置0,而IE不重 置footer的margin-top)。

例如:
分別在Firefox和IE中運行一下代碼,仔細讀者會發現頁腳(footer)的margin-top在火狐中並沒有顯示,而在IE中卻出現了10像素的上邊距。 HTML代碼  引用內容

程序代碼 程序代碼
<body>
<div id="wrapper">
    <div id="masthead">
        masthead content goes here
    </div>
    <div id="sidebar">
        sidebar content goes here
    </div>
    <div id="content">
        main content goes here
        <br/>
        main content goes here
    </div>
    <div id="footer">
        footer
    </div>
</div>

</body>CSS代碼 body {}{
    margin:0; padding:0;
    background-color:#FFFFCC;
}
#wrapper {}{
    width:800px;
    margin:0 auto;
}
/**//*Masthead*/
#masthead {}{
    padding:10px;
    background:#FFCC33;
    margin-bottom:10px;
}
/**//*Content*/
#content {}{
    float:left;
    width:60%;
    background:#CCCCCC;
}
/**//*Sidebar*/
#sidebar {}{
    float:right;
    width:36%;
    background:#999999;
}
/**//*Footer*/
#footer {}{
    clear:both;
    padding:10px;
    background:#FFCC33;
}
arrow
arrow
    全站熱搜

    dancewing 發表在 痞客邦 留言(1) 人氣()