5

Simple tables with CSS grid layout

 2 years ago
source link: https://markheath.net/post/simple-tables-with-css-grid-layout
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Simple tables with CSS grid layout
This website uses cookies to ensure you get the best experience on our website. Learn more
A place for me to share what I'm learning: Azure, .NET, Docker, audio, microservices, and more...

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:

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!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK