2017-09-13 45 views
1

我在html中使用css flexbox創建了3個框,但Chrome使用不同大小的框呈現。以不同寬度呈現的行中的Flex項目

enter image description here

將瀏覽器的邊框以使視圖更小。

感謝您的幫助!

Codepen:https://codepen.io/labanino/pen/rGaNLP

body { 
 
    font-family: Arial; 
 
    font-size: 2rem; 
 
    text-transform: uppercase; 
 
} 
 

 
.flex { 
 
    height: 200px; 
 
    display: flex; 
 
    flex-direction: row; 
 
} 
 

 
.flex>section { 
 
    flex: 1 1 auto; 
 
    display: flex; 
 
    justify-content: center; 
 
    flex-direction: column; 
 
    text-align: center; 
 
} 
 

 
.flex>section:nth-child(1) { 
 
    background: brown; 
 
    margin-right: 20px; 
 
    border: 1px solid #999; 
 
} 
 

 
.flex>section:nth-child(2) { 
 
    background: pink; 
 
    margin-right: 20px; 
 
    border: 1px solid #999; 
 
} 
 

 
.flex>section:nth-child(3) { 
 
    background: green; 
 
    margin-right: 0; 
 
    border: 1px solid #999; 
 
}
<div class="flex"> 
 
    <section>Brown</section> 
 
    <section>Pink</section> 
 
    <section>Green</section> 
 
</div>

回答

1

不要在你的Flex屬性爲您的項目使用auto。使用100%,這將調整彈出框中的寬度,並調整爲添加的任意數量的元素(以防添加超過3個元素)。

.flex > section { 
    flex: 1 1 100%; 
    display: flex; 
    justify-content: center; 
    flex-direction: column; 
    text-align: center; 
} 

他們都不同大小的原因是因爲當你使用auto,它立足於框的內容寬度。這就是爲什麼中間一個沒有那麼寬,因爲'粉紅'這個詞佔用的空間比'綠色'少。

+1

很不錯@Spartacus。感謝您的解釋。 – Labanino

0

這裏是問題的根源:

.flex > section { flex: 1 1 auto } 

這種分解爲:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: auto

使用flex-basis: auto您正在根據內容的長度調整項目大小。因此,更廣泛的內容將創造更多的項目。

如果你想爲行中的所有項目大小相等,然後使用:

  • flex-basis: 0,並
  • min-width: 0/overflow: hidden

隨着flex-basis: 0你分配給每個項目在容器中的空間平均分配。更多細節在這裏:Make flex-grow expand items based on their original size

隨着min-width: 0overflow: hidden你允許項目縮水過去他們的內容,這樣他們就可以在小屏幕上保持相等的大小。更多細節在這裏:Why doesn't flex item shrink past content size?

.flex { 
 
    display: flex; 
 
    height: 200px; 
 
} 
 
.flex>section { 
 
    flex: 1;   /* new; same as flex: 1 1 0 */ 
 
    overflow: hidden; /* new */ 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
    text-align: center; 
 
} 
 

 
/* non-essential demo styles */ 
 
.flex>section:nth-child(1) { 
 
    background: brown; 
 
    margin-right: 20px; 
 
    border: 1px solid #999; 
 
} 
 
.flex>section:nth-child(2) { 
 
    background: pink; 
 
    margin-right: 20px; 
 
    border: 1px solid #999; 
 
} 
 
.flex>section:nth-child(3) { 
 
    background: green; 
 
    margin-right: 0; 
 
    border: 1px solid #999; 
 
} 
 
body { 
 
    font-family: Arial; 
 
    font-size: 2rem; 
 
    text-transform: uppercase; 
 
}
<div class="flex"> 
 
    <section>Brown</section> 
 
    <section>Pink</section> 
 
    <section>Green</section> 
 
</div>

revised codepen

相關問題