2017-08-25 85 views
0

下面的代碼顯示<parent>容器,其中包含一些<child>項目。靈活高度和寬度的Flexbox兒童:100%

<child>項目被定位在<parent>項內部與.flex屬性(見屏幕顯示:撓曲在父)所以它們恰好填滿的父元素。迄今爲止,這一切都很好。

不過,現在我要實現的是,display: flex財產僅適用於<child>項目的高度所以他們完全適合父元素垂直。

對於寬度我希望每個<child>項中的100%周邊母體的所以最終它們被顯示爲塊(下面彼此而不是彼此相鄰)

爲了達到這個目的,我需要更改哪些代碼?

您也可以找到我的代碼here

html { 
 
height: 100%; 
 
} 
 

 
body { 
 
height: 100%; 
 
} 
 

 
.parent { 
 
    height: 80%; 
 
    width: 100%; 
 
    float: left; 
 
    
 
    display: flex; 
 

 
    box-sizing: border-box; 
 
    border-style: solid; 
 
    border-width: 1px; 
 
    background-color: blue; 
 
} 
 

 
.parent div { 
 
    justify-content: space-around; 
 
    flex: 1; 
 

 
    box-sizing: border-box; 
 
    border-style: solid; 
 
    border-width: 1px; 
 
    background-color: green; 
 
}
<div class="parent"> 
 
    <div> 1.0 Menu </div> 
 
    <div> 2.0 Menu </div> 
 
    <div> 3.0 Menu </div> 
 
    <div> 4.0 Menu </div> 
 
</div>

回答

2

更改爲flex-direction: column,他們將垂直堆疊,像塊元素呢,和flex: 1將適用於他們的高度。

另外,justify-content應該設置在parent上,因爲它是flex容器的一個屬性,但是當您在flex-item上使用flex: 1時,它不會影響任何內容。

html, 
 
body { 
 
    height: 100%; 
 
} 
 

 
.parent { 
 
    height: 80%; 
 
    width: 100%; 
 
    display: flex; 
 
    flex-direction: column; 
 
    justify-content: space-around; 
 

 
    box-sizing: border-box; 
 
    border-style: solid; 
 
    border-width: 1px; 
 
    background-color: blue; 
 
} 
 

 
.parent div { 
 
    flex: 1; 
 
    box-sizing: border-box; 
 
    border-style: solid; 
 
    border-width: 1px; 
 
    background-color: green; 
 
}
<div class="parent"> 
 
    <div> 1.0 Menu </div> 
 
    <div> 2.0 Menu </div> 
 
    <div> 3.0 Menu </div> 
 
    <div> 4.0 Menu </div> 
 
</div>

+1

完美。正是我在找什麼。我也在這裏編輯https://jsfiddle.net/onmotyvo/5/ – Michi

1

不過,我現在要實現這一目標顯示:柔性屬性僅適用於項目的高度,使他們完全適合父元素垂直。

對於寬度,我希望每個項目都在周圍父項的100%處,因此最終它們顯示爲塊(彼此下面,而不是彼此相鄰)。

更改flex-direction從默認rowcolumn

flex-direction:column; 

html { 
 
    height: 100%; 
 
} 
 

 
body { 
 
    height: 100%; 
 
} 
 

 
.parent { 
 
    height: 80%; 
 
    width: 100%; 
 
    /* float: left; not required */ 
 
    display: flex; 
 
    flex-direction: column; /* set this */ 
 
    box-sizing: border-box; 
 
    border-style: solid; 
 
    border-width: 1px; 
 
    background-color: blue; 
 
} 
 

 
.parent div { 
 
    justify-content: space-around; 
 
    flex: 1; 
 
    box-sizing: border-box; 
 
    border-style: solid; 
 
    border-width: 1px; 
 
    background-color: green; 
 
}
<div class="parent"> 
 
    <div> 1.0 Menu </div> 
 
    <div> 2.0 Menu </div> 
 
    <div> 3.0 Menu </div> 
 
    <div> 4.0 Menu </div> 
 
</div>