1. 程式人生 > 其它 >網頁佈局--------在一個 div 裡面放多個橫排 div 實現方法 比較一下,flex 最好

網頁佈局--------在一個 div 裡面放多個橫排 div 實現方法 比較一下,flex 最好

目的

目的很簡單,就是實現一個盒子裡面橫向放多個盒子

實現

方法1(最推薦)

給父盒子設定 display: flex;,其他的你就基本不用管了。

.test {
   width: 100%;
   height: 50%;
   display: flex;
}

.box1 {
   width: 20%;
}

.box2 {
   width: 80%;
   background-color: rgb(217, 230, 243);
}
<body>
    <div style="background-color: red;">haaaaaaaaaaaaaaaaaa</div>
    <div class="test">
        <div class="box box1"></div>
        <div class="box box2"></div>
    </div>
    <div style="background-color: red; clear:both">hahahahahahah</div>
</body>

方法2

子元素設定 float: left; 上面不是兩個子元素都有一個類叫 box 嗎,就是幹這個的

 .box {
     height: 100%;
     float: left;
}

結果不變,可自行驗證

方法3

把子元素( 子div )變成行內塊元素

.box {
   height: 100%;
   display: inline-block;
   vertical-align: top;
}

ps:這麼做的話記得不要讓所有子元素的寬等於100%,要小一點,因為變成行內塊元素之間是預設有 小空白 的


同時,記得設定 vertical-align: top; 不然可能會出現這種情況 display:inline-block 出現的元素錯位問題