2017-08-14 136 views
1

我希望Flex容器在父級內展開爲最大尺寸並縮小以適合項目。如何獲取Flex容器以適合內容

在這個例子中,我已經設置了Flex容器的背景顏色來可視化容器。現在它填充父項的整個寬度,但我不想要正確的邊距。

enter image description here

這是我走到這一步:

的Html & CSS

<div class="lc-category-items-wrap"> 
    <section> 
     Obj 1 
    </section> 
    <section> 
     Obj 2 
    </section> 
    <section> 
     Obj 3 
    </section> 
    <section> 
     Obj 4 
    </section> 
    <section> 
     Obj 5 
    </section> 
    <section> 
     Obj 6 
    </section> 
</div> 

.lc-category-items-wrap { 
    display: flex; 
    flex: 1 1 auto; 
    flex-flow: row wrap; 
    justify-content: flex-start; 
    align-items: flex-start; 
} 

.lc-category-items-wrap > section { 
    width: 244px; 
    min-height: 270px; 
} 
+0

使用直列彎曲,以避免在右邊的空白。 – Gerard

回答

0

添加下面的樣式爲.lc-category-items-wrap > section,這樣它會得到streched到整個容器寬度沒有任何餘量。

flex-grow: 1; 
flex-basis: 0; 

Here是的jsfiddle。

1

除非您讓flex-margin的寬度變大,否則沒有「真正的」解決方案。

如果你不想這樣做,我會建議在這種情況下使用justify-content: space-between;justify-content: space-around;

.lc-category-items-wrap { 
 
    display: flex; 
 
    flex: 1 1 auto; 
 
    flex-flow: row wrap; 
 
    justify-content: space-between; 
 
    align-items: flex-start; 
 
} 
 

 
.lc-category-items-wrap>section { 
 
    width: 244px; 
 
    min-height: 270px; 
 
    background: #ddd; 
 
    margin: 5px; 
 
}
<div class="lc-category-items-wrap"> 
 
    <section> 
 
    Obj 1 
 
    </section> 
 
    <section> 
 
    Obj 2 
 
    </section> 
 
    <section> 
 
    Obj 3 
 
    </section> 
 
    <section> 
 
    Obj 4 
 
    </section> 
 
    <section> 
 
    Obj 5 
 
    </section> 
 
    <section> 
 
    Obj 6 
 
    </section> 
 
    <section> 
 
    Obj 7 
 
    </section> 
 
</div>