Equal width columns in CSS Grid

user1678736 picture user1678736 · Dec 1, 2017 · Viewed 44.8k times · Source

I'd like to have the html below showing in n equal columns whether there are two, or three, or more child elements to the row element using css grid - Flexbox makes this easy but I cannot get it done using css grid - any help is appreciated.

<div class="row">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

Answer

tcurdt picture tcurdt · Apr 16, 2020

The common answer of repeat(3, 1fr) is not quite correct.

This is because 1fr is about the distribution of available(!) space. This breaks as soon as the content becomes bigger than the track size. By default, it does not overflow and adjust the column width accordingly. That's why not all 1fr are guaranteed to be of equal width. 1fr is actually rather just a shorthand for minmax(auto, 1fr).

If you really need the columns to be the exact same width you should use:

grid-template-columns: repeat(3, minmax(0, 1fr));

minmax(0, 1fr) allows the grid tracks to be as small as 0 but as large as 1fr, creating columns that will stay equal. But, be aware that this will cause overflows if the content is bigger than the column or cannot be wrapped.

Here is an example that demonstrates the difference.