標籤:導致 code 處理 pad height div src sky width
HTML結構
1 <div class="wrap">2 <div class="div1">1</div>3 <div class="div2">2</div>4 <div class="div3">3</div>5 </div>
CSS樣式
1 .wrap{margin:10px;padding20px;border:5px solid gray;background-color:#fff;}2 .div1{float:left;height:100px;width:100px;background-color:lightgray;}3 .div2{float:left;height:100px;width:100px;background-color:skyblue;}4 .div3{float:left;height:100px;width:100px;background-color:red;}
可以看到外層wrap div的高度並沒有撐起來,這是因為內層元素浮動脫離了文字資料流而導致的,這時我們就需要清除浮動。下面介紹清除浮動的三種常用方法。
1.在最後一個內層元素後面添加空元素,使用clear:both
1 <div class="wrap">2 <div class="div1">1</div>3 <div class="div2">2</div>4 <div class="div3">3</div>5 <div class="clear"></div>6 </div>
1 .clear{clear:both;}
2.給外層元素添加overflow:hidden或者auto屬性。
1 .wrap{2 overflow:auto;3 zoom:1;/*處理相容性問題*/4 }
3.給外層元素添加虛擬元素after,利用after類比建立元素div.clear。(推薦使用,可以作為公用樣式)
1 <div class="wrap clearfix">2 <div class="div1">1</div>3 <div class="div2">2</div>4 <div class="div3">3</div>5 </div>
1 .clearfix{ 2 zoom:1;/*處理ie相容問題*/ 3 } 4 .clearfix:after{ 5 display:block; 6 visibility:hidden; 7 content:‘.‘; 8 clear:both; 9 height:0;10 overflow:hidden;11 }
CSS清除浮動方法