Posted in:

In this post, I want to show how simple the CSS grid makes it to create a basic table layout with control over the column sizes.

In this simple example, I want my table to have two fairly small columns, with a third column being given the bulk of the remaining space.

You can see the result here:

See the Pen Grid Table by Mark Heath (@markheath) on CodePen.

The great thing about this is that thanks to CSS grid (which is available in a healthy majority of browsers now), you can achieve this whole thing with just one simple CSS rule:

.table {
    display: grid;
    grid-template-columns: 1fr 1fr 80%; 
    max-width: 480px;
}

We need to set display to grid (and I've also specified a max-width for my table). Then grid-template-columns is where the intelligent sizing comes in. I'm setting the third column to take 80 percent of the space, and then using fractional units to say that the other two columns should be the same size as each other.

As you can see from the embedded example, this means that if one of the short columns has unexpectedly long content, it doesn't cause the layout of the whole table to be reconfigured. You can also set column widths to auto and it's also worth experimenting with this to see the different results you can achieve.

And that's all there is to it. I added a couple of additional styling properties using the handy nth-child rule to give a different background colour to each column.

But finally after many years of waiting it finally seems easy to create tables in CSS without using the <table> HTML element.

Of course, I should mention that CSS is certainly not my speciality, so feel free to let me know in the comments what the correct/better way to do table layouts in CSS is!

Comments

Comment by Joe Attardi

What about accessibility?

Joe Attardi