Flexbox to fill out row and determine the number of children per row

假如想象 提交于 2020-01-06 00:51:04

问题


I have a bunch of boxes in a container. I don't know how many boxes fit onto a row, the bigger your screen is the more boxes there should be. However I want each row to be fully filled and the boxes resized (within 100px to 150px) to ensure that each row is filled.

http://jsfiddle.net/ssxu5moy/11/

.container2 {
    width:100%;
    height: 100px;
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;
    align-content: stretch;
}

.box {
    border: 1px solid purple;
    background: blue;
    align-self: stretch;
    min-width: 100px;
    max-width: 150px;
}

<div class="container2">
    <div class="box box1">
    </div>
    <div class="box box2">
    </div>
    <div class="box box3">
    </div>
    <div class="box box3">
    </div>
    <div class="box box3">
    </div>
    <div class="box box3">
    </div>
    <div class="box box3">
    </div>
    <div class="box box3">
    </div>
    <div class="box box3">
    </div>
</div>

I already did this in javascript and it works fine, but I thought about changing to flexbox to be simpler, but I'm having difficulty getting it working. Is this even possible in flexbox?


回答1:


Yeah! You can do that. The max-width is making the boxes stop at 150px which appears not what you want as you want each box to fill the remaining space in the row after the wrap right?

Here's an updated fiddle: http://jsfiddle.net/disinfor/ssxu5moy/12/

The only thing I changed in your CSS was the min-width and max-width to the flex property:

CSS:

.box {
    border: 1px solid purple;
    background: blue;
    align-self: stretch;
    flex:1 0 100px;
}

If I understood your question, this should be what you're looking for. Caveat: flex property needs browser prefix.

EDIT: here's some light reading on the flex property shorthand: https://css-tricks.com/almanac/properties/f/flex/

In the event the link is gone: This is the shorthand for flex-grow, flex-shrink and flex-basis (respectively).



来源:https://stackoverflow.com/questions/32774178/flexbox-to-fill-out-row-and-determine-the-number-of-children-per-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!