子div撐不開父div的狀況:css
<style> .example{ background: #008000; width: 400px; margin: 10px; padding: 10px; } .example .childrenDiv{ float: left; height: 100px; width: 100px; word-break: break-all; word-wrap: break-word; } </style> <!--示例--> <div class="example"> <div class="childrenDiv" style="background: #e9b216;">tatatattttaatatatatatatata</div> <div class="childrenDiv" style="background: #df4744;">tatatattttaatatatatatatata</div> </div>
顯示結果:html
解決方法:windows
(一):加<div style="clear:both;"></div>瀏覽器
代碼實例:ide
<!--方法一--> <div class="example"> <div class="childrenDiv" style="background: #e9b216;">tatatattttaatatatatatatata</div> <div class="childrenDiv" style="background: #df4744;">tatatattttaatatatatatatata</div> <!--解決方法--> <div style="clear: both;"></div> </div>
顯示結果:code
分析:htm
父div做爲外部容器,子div設置了float樣式,則外部容器div由於內部沒有clear致使不能被撐開,即內部div由於float:left以後,就丟失了clear:both和display:block的樣式。對象
(二):經過僞元素將父容器撐開it
代碼實例:table
<style> .clearfix:after{ content:"."; display: block; height: 0; clear: both; visibility: hidden; } /* Hides from IE-mac \*/ *html.clearfix{height: 1%;} /*end hide from IE-mac*/ </style> <!--方法二--> <div class="clearfix example"> <div class="childrenDiv" style="background: #e9b216;">tatatattttaatatatatatatata</div> <div class="childrenDiv" style="background: #df4744;">tatatattttaatatatatatatata</div> </div>
顯示結果:
分析:
1.不建議採用第一種方法,首先,代碼中多了一個沒有意義的div;其次,在用dojo作Drag&Drop的時候,因爲這個div是父容器div的一個子節點,若是這個節點被移動,則會形成排版上的錯誤,並且若是要將子div移動到這個div以後,則會由於clear:both被強制換行顯示。
2.方法二原理:after僞對象將在應用clearfix的元素的結尾添加content中的內容,在這裏添加了一個「.」,而且把它的display設置成了block,高度設爲0,clear設爲both,visibility設爲隱藏,即撐開容器。
3.由於windows IE不支持上述作法,因此要在IE上也完美顯示,則必須在clearfix的css定義的後面加一些專門爲IE設定的hack,即:
/* Hides from IE-mac \*/ *html.clearfix{height: 1%;} /*end hide from IE-mac*/
由於轉移符「\」,Mac IE瀏覽器會忽略掉這段hack,但window IE不會,它會應用*html.clearfix{height:1%;}來達到撐開div容器的目的(貌似Mac IE沒有辦法解決這個問題,不顧用戶數量太少,Safari支持就能夠了O(∩_∩)O哈哈~)。
(三)父容器增長一個屬性:overflow:hidden
代碼實例:
<!--方法三--> <div class="example" style="overflow: hidden;"> <div class="childrenDiv" style="background: #e9b216;">tatatattttaatatatatatatata</div> <div class="childrenDiv" style="background: #df4744;">tatatattttaatatatatatatata</div> </div>
顯示結果:
(四)父容器增長一個屬性:display:table
代碼實例:
<!--方法四--> <div class="example" style="display: table;"> <div class="childrenDiv" style="background: #e9b216;">tatatattttaatatatatatatata</div> <div class="childrenDiv" style="background: #df4744;">tatatattttaatatatatatatata</div> </div>
顯示結果: