Data table
Build a data table with table styles.
Data table and border-collapse
The bottom of a sales dashboard usually holds a data table: recent orders, top sellers and the like. Tables show an ugly double border by default; we collapse it into a single line with border-collapse: collapse.
The declaration goes on the table element. Then we add inner padding and a bottom border to cells (th and td).
Zebra stripes and row hover
A zebra-striped table separates rows and boosts readability. We use tr:nth-child(even) to give even rows a light gray tone. To highlight the row under the cursor we use the tr:hover selector and switch its background to a light blue.
This helps the user keep track of which row they're reading; in dense tables that small detail makes a real difference.
Cell styles
We give cells (th and td) inner padding and a bottom border. Header cells (th) end up bold and left-aligned. Inner padding uses padding; the bottom line uses border-bottom.
Instead of styling each cell type separately we use a grouped selector: .data-table th, .data-table td. A single block then styles both cell types.
Exercise Style the data table: .data-table
Add a .data-table block to the stylesheet; give it border-collapse: collapse and width: 100%. Then open a shared block for .data-table th, .data-table td; add padding: 10px, border-bottom and text-align: left. For zebra stripes, give .data-table tbody tr:nth-child(even) a background. For row hover, give .data-table tbody tr:hover a different background.
Show example solution
/* Sales Dashboard stylesheet */
:root {
--bg: #f5f7fa;
--card-bg: #ffffff;
}
.dashboard {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-rows: 60px 1fr;
grid-template-areas:
"sidebar header"
"sidebar main";
}
.sidebar { grid-area: sidebar; }
.header { grid-area: header; }
.main { grid-area: main; }
.kpi-list {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.kpi-card {
background: var(--card-bg);
padding: 16px;
}
.data-table {
width: 100%;
border-collapse: collapse;
}
.data-table th,
.data-table td {
padding: 10px;
border-bottom: 1px solid #e5e9f0;
text-align: left;
}
.data-table tbody tr:nth-child(even) {
background: #f9fafc;
}
.data-table tbody tr:hover {
background: #eaf2ff;
}
Test yourself
-
Which selector do we use to color even rows for a zebra stripe?
- tr:last-child
- tr:nth-child(odd)
- tr:first-child
- tr:nth-child(even)
Show answer
tr:nth-child(even) — Correct. :nth-child(even) selects the even rows.
-
Change the background of the row under the cursor
.data-table tbody tr____ { background: #eaf2ff; }Show answer
.data-table tbody tr:hover { background: #eaf2ff; } -
Match each table declaration to its purpose
- border-collapse
- merge double borders
- nth-child(even)
- select even rows
- tr:hover
- row under cursor
- padding
- cell inner space