css布局—清除浮動的常用方法

來源:互聯網
上載者:User
1 <div class="container">2     <div class="block1">子項目1</div>3     <div class="block2">子項目2</div>4 </div>
.block1{ width:200px;              height:200px;          background: #CBA627;          float:left;          margin-right:10px;}.block2{ width:200px;              height:100px;          background:#009900;          float:left;}

如,在使用div+css寫頁面的時候,經常要使用float樣式進行左右分欄布局。但是在子項目應用float樣式之後,父元素的高度會因為浮動而消失,因此往往需要採取一些方法來清除浮動。現整理方法如下:

(1)浮動元素後面添加空標籤,並為標籤添加樣式{clear:both}如下所示:

<div class="container1">    <div class="block1">子項目1</div>    <div class="block2">子項目2</div>    <div class="clear"></div></div>
/*子項目的樣式不變*/.block1{ width:200px;         height:200px;         background: #CBA627;         float:left;         margin-right:10px;}.block2{ width:200px;         height:100px;         background:#009900;         float:left;}/*新添空標籤的樣式為clear*/.clear{ clear:both;}

(2)為包含浮動元素的父元素添加樣式(如下所示),zoom是為相容ie6:

.container{ overflow:hidden;            zoom:1;}

(3)為包含浮動元素的父元素偽類添加樣式(如下所示),新添樣式缺一不可:

.container:after{ content:" 20";visibility:hidden;display:block;clear:both;height:0;}

(4)為父元素添加樣式{ float:left;},該方法不推薦!!!

 

 

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.