How to Style Table in HTML: Simple CSS Tips and Examples
To style a table in HTML, use
CSS to set properties like border, padding, and background-color on table, th, and td elements. You can add styles inline, in a <style> block, or an external stylesheet to control the table's look.Syntax
Use CSS selectors to target the table, th (table headers), and td (table cells) elements. Common style properties include border for lines, padding for space inside cells, and background-color for colors.
Example selectors:
table- styles the whole tableth- styles header cellstd- styles data cells
css
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 0.5rem;
text-align: left;
}
th {
background-color: #f2f2f2;
}Example
This example shows a simple styled table with borders, padding, and a light background color on headers.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Styled Table Example</title> <style> table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid black; padding: 0.5rem; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <table> <thead> <tr> <th>Name</th> <th>Age</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>Alice</td> <td>30</td> <td>New York</td> </tr> <tr> <td>Bob</td> <td>25</td> <td>Los Angeles</td> </tr> </tbody> </table> </body> </html>
Output
A table with three columns (Name, Age, City) and two rows of data, with black borders around cells, padding inside cells, and a light gray background on the header row.
Common Pitfalls
Common mistakes when styling tables include:
- Not using
border-collapse: collapse;which causes double borders. - Forgetting to add padding, making text cramped.
- Applying styles only to
tablebut not tothortd, so cells look unstyled. - Using inline styles repeatedly instead of CSS classes or selectors.
css
/* Wrong: No border-collapse, no padding */ table { border: 1px solid black; } th, td { border: 1px solid black; } /* Right: Add border-collapse and padding */ table { border-collapse: collapse; } th, td { border: 1px solid black; padding: 0.5rem; }
Quick Reference
Here is a quick cheat sheet for styling tables:
| CSS Property | Purpose | Example Value |
|---|---|---|
| border-collapse | Controls border style between cells | collapse |
| border | Adds border lines | 1px solid black |
| padding | Adds space inside cells | 0.5rem |
| background-color | Sets cell background color | #f2f2f2 |
| text-align | Aligns text inside cells | left, center, right |
Key Takeaways
Use CSS to style
table, th, and td elements for better control.Always add
border-collapse: collapse; to avoid double borders.Add padding to cells to improve readability.
Use background colors on headers to distinguish them visually.
Avoid inline styles; prefer CSS selectors or classes for cleaner code.