CSS allows you to style HTML tables (<table>
, <tr>
, <td>
, <th>
) to improve appearance, spacing, and readability. You can customize borders, colors, spacing, text alignment, and more.
By default, HTML tables have no styling. You can apply borders, padding, and background colors to improve their appearance.
table {
width: 100%;
border-collapse: collapse; /* Removes extra space between borders */
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: left;
}
✔ This adds borders and spacing between table cells.
You can customize border thickness, color, and style.
table {
border: 2px solid black; /* Table border */
}
th, td {
border: 1px dashed gray; /* Cell borders */
}
✔ Border styles: solid
, dashed
, dotted
, double
, etc.
padding
(inside) and border-spacing
(outside) improve table readability.
th, td {
padding: 10px; /* Space inside cells */
}
table {
border-spacing: 5px; /* Space between cells */
}
✔ Padding makes content readable, spacing separates cells.
Alternating row colors enhance readability.
tr:nth-child(even) {
background-color: #f2f2f2;
}
✔ Every second row will have a gray background.
Adding a hover effect improves user experience.
tr:hover {
background-color: lightblue;
}
✔ Rows change color when hovered over.
<th>
)Headers should be bold and visually distinct.
th {
background-color: black;
color: white;
font-weight: bold;
}
✔ Dark header with white text for better contrast.
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: left;
}
th {
background-color: black;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
tr:hover {
background-color: lightblue;
}
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Emma</td>
<td>30</td>
<td>Los Angeles</td>
</tr>
</table>
CSS Property | Description | Example |
---|---|---|
border |
Adds a border around tables, rows, or cells. | border: 1px solid black; |
border-collapse |
Merges table borders into a single line. | border-collapse: collapse; |
padding |
Adds space inside table cells. | padding: 10px; |
border-spacing |
Adds space between table cells. | border-spacing: 5px; |
nth-child(even) |
Styles alternate rows for striping. | tr:nth-child(even) { background: #f2f2f2; } |
hover |
Highlights a row on hover. | tr:hover { background: lightblue; } |
CSS provides full control over table styling. You can customize borders, spacing, row colors, headers, hover effects, and alignment to make tables more readable and visually appealing.
@asadmukhtar