I’m attempting to create a simple grid and have trouble figuring one thing out.
Namely having a few items next to each other how can I merge multiple items into one so they all look "even"?
Here’s how my columns look like right now:
And that’s what I want to achieve:
I want it to be quite universal and work on different resolutions etc. so I’m not sure if flex-grow
will be the best bet here, but seems like in the first row flex-grow: 160
helps and in the last one – flex-grow: 2
also works. But is it the way to go? What if I want ab + bcd + e? I’ll have to calculate flex-grows for every single scenario? Can’t I somehow tell flex to use "basis of X items"?
JSFiddle & SO snippet below.
* {
box-sizing: border-box;
}
.row {
display: flex;
flex-wrap: wrap;
max-width: 460px;
outline: solid 1px #000;
}
.cell {
display: flex;
margin: 10px;
padding: 10px;
background: #eee;
flex: 1 0 70px;
max-width: 100%;
}
<div class="row">
<div class="cell">auto with adjust</div>
<div class="cell">auto with adjust</div>
</div>
<div class="row">
<div class="cell">a</div>
<div class="cell">b</div>
<div class="cell">c</div>
<div class="cell">d</div>
<div class="cell">e</div>
<div class="cell">auto new line + auto full width</div>
</div>
<div class="row">
<div class="cell" style="outline: solid 1px red;">a+b+c+d</div>
<div class="cell">e</div>
</div>
<div class="row">
<div class="cell">a+b</div>
<div class="cell" style="outline: solid 1px red;">c+d+e</div>
</div>
3
Answers
It would be much easier to use
Grid
instead.I found a way to achieve exactly what you want, using Flexbox. It works exactly like Grid and it is fully responsive. I haven’t tested on real content yet, but I’m confident it will work.
I created a few variables:
--nbr
: number of columns (5 in this case)--gap
: the row-gap of the flex grid--col
: the width of a single column in the flex grid.If the grid has 5 columns, then each columns should have a width of
100% / 5 = 20%
.Unfortunately, when
gap
is added, it decreases the width.A grid with 5 columns has 4 gaps.
So the real width of a column is
(100% - (4 * gap)) / 5
.--span
: the value offlex
based on the number of columns merged together.For the record,
flex
is the shorthand forflex-grow
,flex-shrink
andflex-basis
.flex: flex-grow flex-shrink flex-basis
flex-grow
is set to 0 (flex items are not allowed to grow).flex-shrink
is set to 1 (all flex items are allowed to shrink at the same rate).If 3 columns are merged, the final width is
(3 * col) + (2 * gap)
. Which is the value offlex-basis
.--span-1
means the flex-item is merging 1 column,--span-3
means the flex-item is merging 3 columns, …If your flex grid has 12 columns, you should add variables up to
--span-12
.Now you can just assign the
--span
value to every item’sflex
property.I hope all of this makes sense.
Just target each specific
.row
and.cell
in your CSS and useflex-grow
.See
<number>
for valid values. Negative values are invalid. Defaults is 0.