CSS Tables

Styling Tables CSS

Styling tables are so easy in CSS. We can do different things to style the tables. Like putting some borders, changing colors, maybe for different states, etc.

First of all, we have already made a table for demonstration purposes, and we are going to work with that table from now onwards for the example. The table is so easy and straightforward to be made.

To specify the borders of the table, we use the border property for the table, headings, and data cells.

Remember that when we are separating the selectors with a comma, we are grouping them(referred to as grouping of selectors).

You can refer to the below code for understanding the table borders. It is very simple. This is just the CSS from the .css file since you can make a table yourself, but I have given the reference images for the table, to have a look at.

After you put these borders on your table, your table will look something like this –

The above example would generate some weird borders if we remove the border-collapse property. But using that property, we can collapse the borders into single borders, So, if you apply that border-collapse property, then the double border will be collapsed into one.

You can try removing the border-collapse property, and this is how your table would look like-

Now, we will add some more styles like some background color to the heading and the other rows. You can use the following styles for that –

If you have a look at the above properties, we have made the table width to 100%, so the table now stretches to the full available width. Also, about the table header, we have given a background color, and also changed the color of the text.

The nth-child pseudo-class matches the elements based on their position among a group of siblings. Once, we are putting odd as a value, due to which it matches the siblings with odd positions, like 1, 3, 5, 7, etc. Also, we have an even value, due to which it matches the even siblings, like the ones with the even positions, like 2, 4, 6, 8, etc. And, you know about hover right? It is doing the same thing here… like whenever we hover on some row, something happens.

The text that you are seeing just above the table, is the caption. We can set the caption using the caption tag in HTML.

After you apply all these properties, the final look of your table would be something like this –

You can try hovering over the rows and you will see some changes because we have added some styles for the hovering state. You can further modify the table and make it much better.