第二個div高度隨着父div高度改變而改變的幾種實現方式

最近遇到這樣一個需求,一個大的div高度不固定,裏面有兩個小的div,第一個div高度固定(比如爲100px),第二個div高度填滿大div的剩餘高度。實現也很簡單,想到了好幾種實現方式,記錄一下。
因爲外面大的div高度不固定,我在這裏就默認填滿body。
1、定位:外面大的div相對定位,第二個div絕對定位,設置top:100px。代碼如下:outer設置overflow:hidden去掉滾動條。這種方法第二個div的高度和外面大的div的高度一樣。

 <div class="outer">
        <div class="box1"></div>
        <div class="box2"></div>
 </div>
     <style>
        *{
            padding: 0;
            margin: 0;
        }
        html,body{
            height: 100%;
        }
        .outer{
            position: relative;
            width: 100%;
            height: 100%;
            overflow:hidden;
        }

        .box1{
            width: 100%;
            height: 100px;
            background: red;
        }
        .box2{
            position: absolute;
            top: 100px;
            left: 0px;
            bottom: 0px;
            height: 100%;
            width: 100%;
            background: blue;
        }
    </style>

2、設置邊距:外面大的div設置上面的padding爲100px(即第一個div的高度),並且設置爲怪異盒模型(box-sizing:border-box),第一個div設置上面的margin爲-100px。代碼如下:

   <div class="outer">
        <div class="box1"></div>
        <div class="box2"></div>
    </div>
        *{
            padding: 0;
            margin: 0;
        }
        html,body{
            height: 100%;
        }
        .outer{
            width: 100%;
            height: 100%;
            padding-top: 100px;
            box-sizing: border-box;
        }

        .box1{
            width: 100%;
            height: 100px;
            background: red;
            margin-top: -100px;
        }
        .box2{
            height: 100%;
            width: 100%;
            background: blue;
        }

3、採用彈性盒模型flex。直接上代碼:

 *{
           padding: 0;
           margin: 0;
       }
       html,body{
           height: 100%;
       }
       .outer{
           display: flex;
           width: 100%;
           height: 100%;
          flex-direction: column;
       }

       .box1{
           width: 100%;
           height: 100px;
           background: red;
       }
       .box2{
           flex: 1;
           height: 100%;
           width: 100%;
           background: blue;
       }

4、利用css3的計算屬性calc,第二個div的高度等於外面大的div高度減去100。

  *{
        padding: 0;
        margin: 0;
    }
    html,body{
        height: 100%;
    }
    .outer{
        width: 100%;
        height: 100%;
    }

    .box1{
        width: 100%;
        height: 100px;
        background: red;
    }
    .box2{
        height:calc(100% - 100px);
        width: 100%;
        background: blue;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章