Tables are commonly used in web development to display structured data. In this tutorial, you’ll learn how to style HTML tables using CSS to make them visually appealing and improve readability.
HTML Tables
HTML tables consist of rows and columns. A basic table structure looks like this:
1 2 3 4 5 6 7 8 9 10 |
<table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> </table> |
Styling Tables
Basic Table Styling
To remove default table borders and spacing:
1 2 3 4 5 6 7 8 |
table { border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; } |
Table Borders and Cell Padding
1 2 3 4 5 6 7 8 9 10 11 |
/* Custom border and padding */ table.custom { border: 2px solid #333; border-collapse: separate; border-spacing: 10px; } th.custom, td.custom { padding: 10px; border: 1px solid #666; } |
Table Width and Alignment
1 2 3 4 5 |
/* Set table width and center align */ table.centered { width: 80%; margin: 0 auto; } |
Zebra Striping
1 2 3 4 |
/* Zebra striping for better readability */ tr:nth-child(even) { background-color: #f2f2f2; } |
Advanced Table Styling
Highlighting Hovered Rows
1 2 3 4 |
/* Highlight rows on hover */ tr:hover { background-color: #ccc; } |
Responsive Tables
1 2 3 4 |
/* Make tables scroll horizontally on small screens */ table.responsive { overflow-x: auto; } |
Exercises
- Create a table with custom borders and padding.
- Implement zebra striping on a table for improved readability.
- Make a table centered within a container.
Conclusion
In this tutorial, you’ve learned how to style HTML tables using CSS. You can customize table borders, cell padding, alignment, and even create responsive and visually appealing tables. Keep practicing and experimenting to become proficient in table design, as well-designed tables are crucial for displaying data in a clear and organized manner on your web pages.