2016-11-29 19 views
4

我當時在彈性盒中玩耍,想要組合一個行和一個容器。我的問題是:CSS:Flexbox內的Flexbox

爲什麼放置在列中的行元素不跨越flex容器的整個寬度?

的示例代碼如下所示:js-fiddle

HTML:

/* CSS: */ 
 

 
.flex-container { 
 
    color: blue; 
 
    background-color:yellow; 
 
    text-decoration: bold; 
 
    text-size: 1em; 
 
    display: flex; 
 
    justify-content:space-between; 
 
    align-items:center; 
 
} 
 
.horizontal { 
 
    flex-direction:row; 
 
    background-color: red; 
 
} 
 

 
.vertical { 
 
    flex-direction:column; 
 
}
<body> 
 
    <div class="flex-container vertical"> 
 
    <div class=flex-item>1 </div> 
 
    <div class=flex-item>2 </div> 
 
    <div class="flex-container horizontal" > 
 
    <div class=flex-item>3a </div> 
 
    <div class=flex-item>3b </div> 
 
    <div class=flex-item>3c </div> 
 
    </div> 
 
    <div class=flex-item>4 </div> 
 
    <div class=flex-item>5 </div> 
 
    </div> 
 
</body>

感謝您的幫助!

+1

因爲你'.horizo​​ntal'容器不夠寬。添加'寬度:100%;'。 – Roberrrt

+0

那麼這是相當直接;)我以爲我曾試過.. –

+0

呵呵,我很抱歉。咖啡還沒有被踢出去。我也不知道寬度爲什麼不會自動限制,因此將其作爲註釋發佈,直到找到解決方案。 – Roberrrt

回答

0

這是因爲Flexbox的工作原理。

由於.horizontal容器本身是一個彈性兒童,它會自動調整到其他孩子的大小。只允許騰出內容的空間,這是.horizontal本身的孩子。

手動應用的寬度將導致該項目正在創建的空間,而justify-content: space-between將在踢

解決方案,更改以下規則:既然你已經設定align-items:center;

.horizontal { 
    flex-direction: row; 
    background-color: red; 
    width: 100%; 
} 
+0

謝謝,這會產生所需的結果。來自Danield的解決方案也生產寬行,但元素不再中心對齊 –

2

柔性容器除了居中 - 這些物品也只佔用他們需要的最小空間量。

如果您尚未設置此屬性 - 那麼默認值stretch將會踢入,並且項目佔用全部寬度。

然後,就像@Michael_B指出的那樣,您可以在彈性項目上應用align-self:center以將項目置於橫軸上。

.flex-container { 
 
    color: blue; 
 
    background-color: yellow; 
 
    text-decoration: bold; 
 
    text-size: 1em; 
 
    display: flex; 
 
    justify-content: space-between; 
 
} 
 

 
.horizontal { 
 
    flex-direction: row; 
 
    background-color: red; 
 
} 
 

 
.vertical { 
 
    flex-direction: column; 
 
} 
 

 
.flex-item { 
 
    align-self: center; 
 
    /* center each flex item along the cross axis */ 
 
    text-align: center; 
 
    /* horizontally center content within flex item */ 
 
}
<body> 
 
    <div class="flex-container vertical"> 
 
    <div class=flex-item>1 </div> 
 
    <div class=flex-item>2 </div> 
 
    <div class="flex-container horizontal"> 
 
     <div class=flex-item>3a </div> 
 
     <div class=flex-item>3b </div> 
 
     <div class=flex-item>3c </div> 
 
    </div> 
 
    <div class=flex-item>4 </div> 
 
    <div class=flex-item>5 </div> 
 
    </div> 
 
</body>

+0

您能否詳細說明爲什麼在'.horizo​​ntal'上應用'align-items:stretch'不起作用? – Roberrrt

+1

@Roberrrt除了您需要注意發生的拉伸位於**橫軸**上,所以當彎曲方向爲列時 - 水平伸展發生,並且當彎曲方向爲行時 - 拉伸垂直髮生 – Danield

+1

這個答案指出了推理。對於純粹的柔性解決方案,從容器中移除'align-items:center'。將'align-self:center'添加到您想居中的Flex項目。中間項目(3a/b/c)將默認伸展:https://jsfiddle.net/cq0ecd5u/2/ –