使用float浮動以後,父元素「塌陷」的解決辦法

經常在並排div的時候使用到float屬性,可是使用以後會發現他們的父元素會沒有高度,以後的元素會「擠上來」,形成「塌陷」。html

好比,咱們想要的以下效果:spa

代碼以下:code

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <style>

 .father-div{
            background-color: #000000;
 }
        .items{
            margin: 10px;
 float: left;
 height: 100px;
 background-color: #FF0000;
 }
        .next-div{
            background-color: #0099FF;
 height: 100px;
 }
    </style>
    <body>
        <div class="father-div">
            <div class="items">第一個</div>
            <div class="items">第二個</div>
            <div class="items">第三個</div>
        </div>
        <div class="next-div">next-div</div>
    </body>
</html>

卻發現實際運行效果是這樣的:htm

能夠看到,father-div本應該包裹三個items,可是它的高度卻消失了。it

出現這種狀況的時候,咱們能夠經過以下幾種方法來解決:class

  1. 在father-div里加入height屬性,該方法適用於子元素高度已知而且固定的狀況。
    meta

  2. 在最後一個子元素後加入<div style="clear:both;"></div>,清除浮動元素。float

  3. 在father-div里加入overflow:hidden屬性。方法

這裏推薦後兩種方法。im

相關文章
相關標籤/搜索