CSS Tutorial
CSS Tables
Plain HTML tables look cramped, but a little CSS makes them clean and readable. You can control borders, spacing, alignment, and add striped rows or hover highlights to guide the eye.
Styling tables
A table is built from rows <tr>, header cells <th>, and data cells <td>. By default every cell draws its own separate border, leaving gaps. CSS lets you merge those borders, add breathing room, and colour rows so large tables stay easy to scan.
Borders and border-collapse
Add a border to th and td to draw grid lines. Then set border-collapse: collapse on the table so adjacent borders merge into a single crisp line instead of doubled edges.
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
font-family: system-ui, sans-serif;
}
th, td {
border: 1px solid #94a3b8;
padding: 10px 16px;
text-align: left;
}
</style>
</head>
<body>
<table>
<tr><th>Role</th><th>City</th></tr>
<tr><td>Frontend Intern</td><td>Pune</td></tr>
<tr><td>Data Analyst</td><td>Bengaluru</td></tr>
</table>
</body>
</html>| Property | Purpose |
|---|---|
| border-collapse | Merge (collapse) or separate cell borders |
| border-spacing | Gap between cells when borders are separate |
| padding | Space inside each cell |
| text-align | Horizontal alignment of cell text |
| vertical-align | Vertical alignment of cell content |
Zebra-striped rows and header colour
Alternating row colours make wide tables far easier to read. The :nth-child(even) selector targets every second row, and a coloured <th> row anchors the top.
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
font-family: system-ui, sans-serif;
}
th, td { padding: 10px 14px; text-align: left; }
th { background: #2563eb; color: white; }
tr:nth-child(even) { background: #eef2ff; }
tr:hover { background: #dbeafe; }
</style>
</head>
<body>
<table>
<tr><th>Name</th><th>Score</th></tr>
<tr><td>Asha</td><td>92</td></tr>
<tr><td>Ravi</td><td>88</td></tr>
<tr><td>Meera</td><td>95</td></tr>
<tr><td>Karan</td><td>81</td></tr>
</table>
</body>
</html>Full width and responsive scrolling
Set width: 100% to make a table fill its container. On small screens wrap a wide table in a scrolling box so it never breaks the layout.
.table-wrap {
overflow-x: auto; /* horizontal scroll on small screens */
max-width: 100%;
}Use CSS tables only for tabular data. Do not use <table> elements to build page layout — that is what flexbox and grid are for.
Key points
- border-collapse: collapse merges doubled borders into single lines.
- Add padding to cells so text is not cramped against the borders.
- tr:nth-child(even) creates zebra stripes for readability.
- Wrap wide tables in an overflow-x: auto container to stay responsive.
