How to align table columns
Short answer
text-align sets the text alignment in a cell. Numbers are usually aligned to the right so the digits line up:
<style>
table { border-collapse: collapse; }
th, td { padding: 6px 12px; border-bottom: 1px solid silver; text-align: left; }
.num { text-align: right; }
</style>
<table>
<tr><th>Product</th><th class="num">Price</th></tr>
<tr><td>Tea</td><td class="num">$3.50</td></tr>
<tr><td>Coffee</td><td class="num">$12.00</td></tr>
</table>A whole column at once
To avoid putting a class in every cell, select the column by its number with :nth-child:
<style>
td, th { padding: 4px 12px; }
td:nth-child(2), th:nth-child(2) { text-align: right; font-variant-numeric: tabular-nums; }
</style>
<table>
<tr><th>Day</th><th>Visitors</th></tr>
<tr><td>Monday</td><td>1,120</td></tr>
<tr><td>Tuesday</td><td>98</td></tr>
</table>font-variant-numeric: tabular-nums makes all digits the same width — number columns look neater.
Vertically
If neighboring cells have a different number of text lines, vertical-align: top aligns the content to the top of the cell instead of the middle.
Common mistake
The column is aligned by setting text-align on a <col> or <colgroup> element. Columns accept only width, background and border — text alignment is not passed to the cells through them. A cell selector is needed.
Functions used in this recipe
- text-align — Horizontal alignment of text and inline content inside a block.
- vertical-align — Vertical alignment of an inline element within a line, or of content in a table cell.
- :nth-child() — Matches children by their position: the third, every even one, every third one.
- <td>, <th> — Table cells: `<td>` holds data, `<th>` is a header cell.
- font — A shorthand that sets the style, weight, size, line height and family of the font in one line.