As soon as upon a time (roughly 2013), I wrote a jQuery plugin to calculate equal top columns. It ensured that the very particular situation of a row with three columns would maintain the content material containers equal top regardless of the size of the content material they contained. The dominant structure methodology on the time – floats – didn’t deal with this downside.
When flexbox arrived on the scene, this grew to become doable with:
.flexbox {
show: flex;
}
Wonderful! By default, direct kids line up in a row and have a “stretch” utilized so they’re equal top 🙌
However then you definately add two .column
divs as kids and… the contents of the columns seem unequal once more 😔
The repair is:
.flexbox {
show: flex;// Guarantee content material components replenish the .column
.ingredient {
top: 100%;
}
}
Now the columns will seem equal top and develop with the content material of .ingredient
.
With grid, we encounter related conduct:
.grid {
show: grid;
// Primarily change the default axis
grid-auto-flow: column;
}
Just like flexbox, direct kids will likely be equal top, however their kids want the peak definition added identical to within the flexbox resolution:
.grid {
show: grid;
grid-auto-flow: column;// Guarantee content material components replenish the .column
.ingredient {
top: 100%;
}
}
This is a demo of each options, in addition to further demos for outlining a set quantity of columns per row as described beneath:
By Stephanie Eckles (@5t3ph)
For purely fixing for equal top components, the benefit of flexbox is the default axis instantly allows side-by-side columns, whereas grid must be explicitly set. Nevertheless, components is not going to inherently be equal-width as properly (which can be a bonus relying on kind of content material, for instance navigation hyperlinks).
The benefit of grid is inherently equal-width components if that’s fascinating. A further benefit is when you do not need auto-flow however as an alternative need to outline a set max variety of columns per “row”. On this case, grid structure simply handles the mathematics to distribute the columns vs. a flexbox resolution requiring defining the calculation to limit the variety of columns.
Updating our .grid
resolution to deal with for outlining a max variety of 3 .column
per row is so simple as:
&.col-3 {
hole: $col_gap;
grid-template-columns: repeat(3, 1fr);
}
Whereas one (very fundamental) choice for flexbox can be:
$col_gap: 1rem;.flexbox.col-3 {
// Explicitly must be outlined to wrap
// overflow gadgets to the following digital row
flex-wrap: wrap;
.column {
// "hack" for no hole property
margin: $col_gap/2;
// outline calculation for browser to make use of on the width
max-width: calc((100% / 3) - #{$col_gap});
}
}
You’ll additionally want to think about how these options are dealt with responsively, however that is a bit out of scope of this text 🙂