<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清除浮動三種方式</title> <style type="text/css"> .list0{ width: 210px; border: 1px solid #000; list-style: none; margin: 50px auto 0px; padding: 0px; } .list0 li{ float: left; width: 50px; height: 50px; margin:8px; border: 1px solid gold; background-color: cyan; line-height: 50px; text-align:center; } .list{ width: 210px; /*height: 200px;*/ border: 1px solid #000; margin: 50px auto 0px; list-style: none; padding: 0px; /*overflow: hidden;*/ /* 這是第一種解決方法 */ } .list li{ float: left; width: 50px; height: 50px; background-color: plum; border:1px solid aqua; margin: 9px; line-height: 50px; text-align: center; } /* .clearfix:after{ content: ""; display: table; clear:both; }*/ /*第三種解決方法*/ /*與top塌陷一起寫*/ /*第一種寫法*/ /* .clearfix:after{ content: ""; clear: both; display: table; } .clearfix:before{ content: ""; display: table; } */ /*精簡寫法*/ /*.clearfix:before,after{*/ /* 此處不能夠簡寫元素名,每一個偽類名前面必須有所跟隨的類名 */ .clearfix:before, .clearfix:after{ content: ""; display: table; } .clearfix:after{ clear: both; } .clearfix{ zoom:1; } /*兼容IE瀏覽器語句.新版Edge可不用*/ body div strong{ color: black; } </style> </head> <body> <div style="color: gray;"> 在父集沒有設置高度的時候,子集設置浮動.則不能夠撐起父集的邊框,形成bug.(類似top塌陷) </div> <ul class="list0"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <br> <br> <br> <br> <br> <div style="color: gray;"> <=====這個時候需要清除浮動.<br> <br> <br> 有三種解決方法:<br> 1.父集添加<strong>overflow:hidden;</strong>來撐起邊框.但此方法會有負面影響.<br> 2.在子元素最后添加一個空的div塊元素,並且添加行內樣式為style="clear:both;"##例如:<strong><div style="clear: both;"></div></strong><br> 3.在style式樣中添加專門針對此bug的解決式樣.類似於第二種方式.不過不影響子集元素,且能夠重復利用. <strong> <br> .clearfix:after{ <br> content: ""; <br> display: table; <br> clear:both;} </strong> <br> 並且在通常時候是與防top塌陷的bug是同時寫入,在需要的時候一起用.<br> ===>最成熟的方法<=== <br> <strong> .clearfix:before, .clearfix:after{<br> content: "";<br> display: table; } <br> .clearfix:after{<br> clear: both; }<br> </strong> ===>最成熟的方法<=== <br> </div> <ul class="list clearfix"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> <li>12</li> <li>13</li> <li>14</li> <li>15</li> <li>16</li> <li>17</li> <li>18</li> <li>19</li> <li>20</li> <li>21</li> <!-- <div style="clear: both;"></div> --> <!-- 這是第二種解決方法 --> </ul>
</body> </html>
塌陷是因為, 父元素屬於文檔流, 子元素浮動, 導致父元素無法捕捉子元素的高度, 導致自身高度為0.
解決思路有三:
1. 在子元素后添加一個新元素, 撐開高度.
2. overflow隱藏子元素
3. 使用clearfix(:alter或before)增加偽元素, 在不影響排版內容的情況下解決問題.