We used to do a lot of column-based layouts at work — which I implemented with CSS Grid.
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
This example can be customized to any number of columns by changing the 3
in repeat(3, 1fr)
.
All was fine initially, but designers complained of inconsistent column widths on certain screen sizes.
After some research, I stumbled over this solution and it works great!
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
As stated in the answer, the minmax(0, 1fr)
function makes the columns be between 0
and 1fr
and forces the columns to be the same width.
Bonus tip!
----------------------
| | | |
| | | |
| | | |
----------------------
| | | |
| | | |
| | | |
----------------------
| | | |
| | | |
| | | |
----------------------
For a grid that needs single-pixel borders between the columns and/or rows, you can use the gap
property together with background-color
and it will keep working even if wrapping occurs.
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1px;
background-color: black;
}
.grid > * {
background-color: white;
}