CSS Techniques for Styling HTML Tables
Learn how to style HTML tables using CSS.
In the past, tables were often misused for page layout purposes. However, with the introduction of Grid and Flexbox in CSS, tables can now be used specifically for styling tabular data.
To start, let’s look at a basic HTML table:
1 | <table> |
By default, tables have a plain appearance, with the browser applying some default styles:
To style the table and its elements, we can use CSS.
To add a border, we can target the table
, th
, and td
elements and set the border
property:
1 | table, th, td { |
When combined with some margin, this creates a more visually appealing table:
Another common requirement is to apply different background colors to alternating rows. This can be achieved using the :nth-child(odd)
and :nth-child(even)
selectors:
1 | tbody tr:nth-child(odd) { |
This results in a visually distinct table:
Moreover, by adding the border-collapse: collapse;
property to the table element, all borders will collapse into a single line:
By applying these CSS techniques, you can easily style your HTML tables to match the look and feel of your website.
tags: [“CSS”, “HTML”, “table styling”]