Tables are a fundamental way to organize and display data on web pages. With CSS, you can transform plain HTML tables into visually appealing, professional-looking components that enhance user experience.
Basics of HTML Tables
Before diving into CSS styling, let’s review the structure of an HTML table:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Jane</td>
<td>25</td>
<td>London</td>
</tr>
</tbody>
</table>
This table contains a header (<thead>
), body (<tbody>
), rows (<tr>
), and cells (<th>
and <td>
).
Styling Tables with CSS
Adding Borders
Adding borders to tables and cells makes the data more readable:
table {
border-collapse: collapse; /* Merge borders */
width: 100%;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
Styling Headers
Table headers can stand out with background colors and bold text:
th {
background-color: #f4f4f4;
font-weight: bold;
color: #333;
}
Alternating Row Colors
For better readability, apply zebra striping:
tr:nth-child(even) {
background-color: #f9f9f9;
}
Adding Hover Effects
Highlighting rows on hover improves interactivity:
tr:hover {
background-color: #f1f1f1;
}
Fixed Table Layout
Prevent layout shifts by setting a fixed table layout:
table {
table-layout: fixed;
}
td {
word-wrap: break-word; /* Ensure content wraps */
}
Styling Borders
Customize borders for a polished look:
table {
border: 2px solid #000;
border-spacing: 0;
}
td, th {
border: 1px solid #ddd;
}
Advanced Table Styling
Merging Cells
Use the colspan
and rowspan
attributes in HTML to merge cells:
<tr>
<td colspan="2">Merged Cell</td>
</tr>
Highlighting Columns
Apply styles to specific columns with the nth-child
pseudo-class:
td:nth-child(2) {
color: blue;
font-weight: bold;
}
Responsive Tables
Make tables responsive by enabling horizontal scrolling:
table {
width: 100%;
border-collapse: collapse;
}
.table-wrapper {
overflow-x: auto;
}
td, th {
white-space: nowrap;
}
Wrap your table inside a div
with the table-wrapper
class for this to work:
<div class="table-wrapper">
<table>...</table>
</div>
Conclusion
CSS tables offer versatility in presenting data. By combining these techniques, you can create clean, organized, and visually appealing tables suitable for any website. Whether for simple data displays or complex dashboards, CSS styling makes tables more user-friendly and engaging.