簡體   English   中英

使用 flexbox 實現等高的列

[英]achieving equal height columns with flexbox

我正在嘗試構建一個具有兩個單獨內容組的布局:一個在左側和右側,目前具有固定寬度 (20%/80%)。 在每一邊,我都試圖通過使用 flexbox: left panel with flex-direction: column和右面板 with flex-direction: row wrap來排列內容。 每邊的內容數量可以是靈活的。 內容較少的面板應與另一個“較高”側的高度相匹配。

到目前為止,我已經能夠實現基本布局,如這個jsfiddle所示。 但是,我的問題是,即使我將高度設置為 100%,我也無法制作“較短”面板來填充高度。 在給定的示例中,左側面板的 'C' div 和右側面板的 'Box7' div 之間有一個空白空間。 html/css 代碼如下所示。

我該如何解決這個問題,或者有更好更簡單的布局解決方案嗎? 任何幫助,將不勝感激。

HTML

<div class='top'>
    <div class='left'>
        <div class='litem'>A</div>
        <div class='litem'>B</div>
        <div class='litem'>C</div>
    </div>
    <div class='right'>
        <div class='ritem'>Box 1</div>
        <div class='ritem'>Box 2</div>
        <div class='ritem'>Box 3</div>
        <div class='ritem'>Box 4</div>
        <div class='ritem'>Box 5</div>
        <div class='ritem'>Box 6</div>
        <div class='ritem'>Box 7</div>
    </div>
</div>

CSS

* { outline: 1px solid Grey; }

html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    background-color: Cornsilk;
}

.top {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 100%;
}

.left {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    width: 20%;
    height: 100%;
}

.right {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    width: 80%;
    height: 100%;
}

.litem, .ritem {
    margin: 0;
    padding: 0;
}

.litem { height: 50%; }
.ritem { height: 50%; width: 33.3%;}

.litem:nth-child(1) { background-color: Cyan; }
.litem:nth-child(2) { background-color: DarkCyan; }
.litem:nth-child(3) { background-color: DarkSeaGreen; }

當您將height: 100%應用於htmlbody ,您將子元素的增長限制為屏幕的 100%。

在您的代碼中,您的.left flex 項目確實按照指定拉伸到height: 100% .left周圍添加邊框以進行說明: DEMO

如果您刪除所有固定高度,您將啟用 flex 容器以根據默認設置拉伸所有 flex 項目: align-items: stretch (創建等高列的設置)。 演示

當您將flex: 1添加到.left彈性項目 ( .litem ) 時,它們會在它們之間均勻分配容器中的所有可用空間。 演示

簡而言之,當您使用height屬性時,您會覆蓋align-items: stretch ,即等高列的 flex 設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM