Chuyển đến nội dung

Bài 88 · Lists, Tables and Forms

Styling Tables

Make data tables readable with CSS. Learn border-collapse, padding, zebra striping, number alignment, sticky headers, table-layout and responsive scrolling tables.

A table with no CSS is a grid of cramped text with no lines, no rhythm and no clear headers. With a dozen declarations you can turn it into something people can actually scan: clear row separation, aligned numbers, a header that stays visible while you scroll, and a layout that doesn't break the page on a phone.

This lesson assumes you already know the table markup (<table>, <caption>, <thead>, <tbody>, <th>, <td>) from Tables and Table Headers and Captions. Here we focus purely on the CSS.

Borders and border-collapse

Put a border on table cells and you get a surprise: every cell has its own box, with a small gap between neighbors, so you see doubled lines. That's the default model, border-collapse: separate.

Switch to border-collapse: collapse and adjacent cells share a single border. This is what you want for almost every data table.

CSS
table { border-collapse: collapse; }
th, td { border: 1px solid #cbd5e1; }

In the separate model, you control the gap with border-spacing (one value for both directions, or two for horizontal then vertical). It's useful for card-like rows, where each row floats on its own with rounded corners. border-spacing is ignored once borders collapse.

separate vs collapse

Change border-spacing to 0 on the first table and you'll see doubled lines touching each other. That's why collapse is the usual choice.

A clean, readable data table

Modern table design usually drops most of the lines. Horizontal rules between rows, generous padding, and a distinct header row are enough. Here are the ingredients:

  • Padding on th and td. Around 0.5rem 0.75rem is a comfortable start.
  • Text alignment. Headers are centered by default; left-align them to match the data. Numbers should be right-aligned so the digits line up.
  • Tabular figures. font-variant-numeric: tabular-nums makes every digit the same width, so columns of numbers align perfectly.
  • Vertical alignment. vertical-align: top on cells keeps multi-line rows tidy (the default is middle).
  • Zebra striping with :nth-child(even) on rows, which helps the eye track across wide tables.
  • Row hover for interactive tables, so people can see which row their pointer is on.
A polished data table

Notice the header cells for numeric columns are right-aligned too, so the label sits above the digits. Also notice the border-bottom is on the <tr>. Row borders only show up when borders collapse; in the separate model rows can't have borders at all.

Stripe the body, not the table. Write tbody tr:nth-child(even) rather than tr:nth-child(even). Otherwise the header row counts as row one and the striping shifts whenever you add or remove a header row. Structural Pseudo-classes explains how :nth-child() counts.

Styling columns

You might expect to style a column with a selector, but cells don't live inside columns in the DOM; they live inside rows. You have two tools:

  • <col> and <colgroup> can take only a handful of properties: background, border (when collapsed), width and visibility. Good for a tinted column, nothing more. See Column Groups.
  • :nth-child() on cells, like td:nth-child(3), selects the third cell in every row. It works for any property, as long as no cells span columns.

The .num class in the example above is a third option, and the most robust one: explicit, readable, and immune to column reordering.

Controlling column widths: table-layout

By default, tables use table-layout: auto: the browser reads every cell's content before it decides how wide each column should be. That gives good results, but long words or URLs can stretch a column, and very large tables must load fully before they settle.

table-layout: fixed decides column widths from the table's width and the first row only (or from <col> widths). The rest of the content has to fit. Combine it with width: 100% and per-column widths, and the layout becomes predictable and fast. Long text then needs overflow-wrap: anywhere or text-overflow: ellipsis to stay inside its cell (both are covered in Wrapping, Overflow and Hyphens).

CSS
.log {
  table-layout: fixed;
  width: 100%;
}
.log th:nth-child(1) { width: 9rem; }  /* timestamp */
.log th:nth-child(2) { width: 5rem; }  /* level */
/* the message column takes whatever is left */
.log td { overflow-wrap: anywhere; }

Sticky headers

For long tables, keep the header row on screen with position: sticky. Apply it to the <th> cells (sticking <thead> itself also works in modern browsers, but cells are the most reliable), and give them a background so rows don't show through as they scroll underneath.

The sticky header sticks to its nearest scrolling ancestor. In a page-length table that's the viewport. If the table sits inside a scroll box, it sticks to the top of that box, which is exactly what the next example does. Positioning covers sticky in depth.

Sticky header in a scroll box

The divider under the header uses an inset box-shadow instead of a border. With collapsed borders, a cell's border belongs partly to the table grid and doesn't always travel with the sticky cell, so a shadow is the dependable way to draw that line.

Responsive tables

Tables are wide by nature, and a phone screen is narrow. You have three honest options:

  1. Let it scroll horizontally. Wrap the table in a container with overflow-x: auto. This keeps the table a table, which is the most accessible option. Make the wrapper focusable (tabindex="0") with a label, as in the example above, so keyboard users can scroll it too.
  2. Reduce what you show. Hide low-priority columns on small screens with a media query or container query, and offer the full data elsewhere.
  3. Restack rows as cards. At narrow widths, set the table elements to display: block and show each cell's header with content: attr(data-label). This looks good, but changing display on table elements can strip table semantics in some browsers, so add explicit ARIA roles (role="table", role="row", role="cell") if you go this way, and test with a screen reader.

For most data, option 1 is the right default: it costs three lines of CSS and changes nothing for assistive technology.

CSS
.table-wrap {
  overflow-x: auto;
}
.table-wrap table {
  min-width: 36rem; /* below this, scroll instead of squashing */
}

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why do cell borders look doubled on an unstyled table?

    Separate borders give each cell its own box. border-collapse: collapse merges neighboring borders into one.
  2. 2. Which declaration makes digits in a column line up perfectly?

    Tabular figures give every digit the same width. Combined with right alignment, the place values line up.
  3. 3. What does table-layout: fixed base column widths on?

    Fixed layout ignores later rows, which makes rendering fast and predictable, but long content must be wrapped or truncated.
  4. 4. A sticky <th> lets rows show through it while scrolling. What is missing?

    Sticky cells are transparent by default, so the rows scrolling underneath are visible. Give them a solid background.
  5. 5. What is the most accessible default for a wide table on a small screen?

    Horizontal scrolling keeps real table semantics. A focusable, labeled wrapper lets keyboard users scroll it too.

Summary

  • Use border-collapse: collapse for data tables; border-spacing only applies in the separate model.
  • Padding, start-aligned text, right-aligned tabular-nums numbers and light row dividers make tables scannable.
  • Stripe rows with tbody tr:nth-child(even) so header rows don't shift the pattern.
  • table-layout: fixed gives fast, predictable column widths from the first row.
  • position: sticky; top: 0 on header cells, plus a background, keeps headers visible.
  • On narrow screens, a scrollable, focusable wrapper is the safest responsive table.

Next: Styling Forms, where you will make inputs, checkboxes and validation messages look consistent and stay accessible.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.