CSS Tables
Default HTML tables look dated. A handful of CSS properties turn them into the clean tables you see everywhere on the modern web.
The properties that actually matter
| Property | Why you need it |
|---|---|
border-collapse: collapse | Merges adjacent cell borders into a single line. Almost always what you want. |
width: 100% | Lets the table fill its container. |
th, td { padding } | Gives the data room to breathe. |
tbody tr:nth-child(even) | Zebra stripes for scanning long tables. |
caption-side: bottom | Move the table caption below the table. |
border-spacing | Only useful when not collapsing borders. |
A solid starting point
CSS
table {
border-collapse: collapse;
width: 100%;
font-size: 14px;
}
th, td {
border: 1px solid #ddd;
padding: 9px 11px;
text-align: left;
vertical-align: top;
}
th { background: #f1f1f1; font-weight: bold; }
tbody tr:nth-child(even) td { background: #fafafa; }
tbody tr:hover td { background: #f1faf5; }
Tip: On phones, wrap the table in
<div style="overflow-x: auto">. Long tables scroll horizontally instead of breaking the layout.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Tables</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Merge adjacent cell borders into a single line.
table { border-
: collapse; width: 100%; }
The property is named after what it does.
Discussion
Loading…