2016-02-12 48 views
2

我有一個3個孩子的柔性容器。對每個子女max-widthmin-width進行設置,以便在屏幕尺寸發生變化時,我可以讓他們看起來不失體面。如果Flex項目被強制設置爲新行時,Flex項目如何保持相同的尺寸?

.container{ 
 
    display: flex; 
 
    flex-flow: row wrap; 
 
    justify-content: space-between; 
 
    margin-right: -10px; 
 
} 
 

 
.child{ 
 
    flex-grow: 1; 
 
    max-width: 450px; 
 
    min-width: 350px; 
 
    margin-top: 10px; 
 
    margin-right: 10px; 
 
    background: blue; 
 
    height: 400px; 
 
}
<div class="container"> 
 
    <div class="child"> 
 
    test content 
 
    </div> 
 
    <div class="child"> 
 
    test content 
 
    </div> 
 
    <div class="child"> 
 
    test content 
 
    </div> 
 
</div>

的問題是,當屏幕變得如此之小,孩子1被強制到一個新行,它不具有的大小與其他2名兒童在它上面相同: enter image description here

有沒有辦法強制新行上的孩子與兄弟姐妹具有相同的寬度?

小提琴:https://jsfiddle.net/1ekdkbvk/

+0

'最大寬度:350像素;'和'最小寬度:350像素;'? –

+0

這是不是很清楚你在問什麼。在紅色箭頭的上方圖像中,第一行的框接近其允許的最小寬度('min-width:350px'),第二行的框接近其允許的最大寬度('max-width: 450px')。佈局完全符合你的要求。你想在盒子上做什麼?是一個固定的寬度? –

+0

@Michael_B:我想有辦法讓第三個盒子的寬度鏡像第一個和第二個盒子的寬度。我不希望盒子的寬度是固定的,因爲通過設置「min-width」和「max-width」,盒子始終保證在這些尺寸範圍內(這是使內容可讀的範圍)。 – F21

回答

0

也許在最後的插槽中一種無形的柔性項目會爲你工作。

將此代碼添加到您的CSS:

.container::after { 
    content: ""; 
    flex-grow: 1; 
    max-width: 450px; 
    min-width: 350px; 
} 

DEMO


UPDATE

我忘了補充一個規則,這就造成了輕微溢出的權僞元素。

.container::after { 
    content: ""; 
    flex-grow: 1; 
    max-width: 450px; 
    min-width: 350px; 
    margin-right: 10px;  /* to match the other flex items */ 
} 

REVISED DEMO


更多細節在此相關帖子:Properly sizing and aligning the flex item(s) on the last row

+0

謝謝!我有一種感覺,我不得不冒出額外的元素來實現這一點。我使用媒體查詢添加它,以便當屏幕有很多寬度時,您不會在右側獲得空白插槽。 – F21

+0

快速更新:左下角的元素(請參閱您的小提琴)將始終略大於預期值。無論如何解決這個問題? – F21

+0

下面是一個更準確的小提琴展示問題:https://jsfiddle.net/w03ckz7c/1/ – F21

0

只是刪除flex-grow: 1;.child將解決您的問題。

.child{ 
    max-width: 450px; 
    min-width: 350px; 
    margin-top: 10px; 
    margin-right: 10px; 
    background: blue; 
    height: 400px; 
} 

Working Fiddle

或其它溶液:

使用flex-basis: 100%;.child

Fiddle

+1

如果我刪除'flex-grow:1',即使有空間,孩子們也不會再擴大到它的最大寬度爲450px。如果我添加「flex-basis:100%」,那麼孩子們在包裝到新排之前不會試圖縮小體型。 – F21