CSS can greatly enhance the appearance of HTML tables, making them more visually appealing and easier to read. Here’s a detailed explanation of some common CSS properties used for styling tables:
• border
• border-collapse
• padding
• width
• height
• text-align
• color
• background-color
The border property sets the border around table elements (e.g., <table>, <th>, <td>). It can define the border’s width, style, and color.
table {
border: 2px solid black;
}
th, td {
border: 1px solid gray;
}
The border-collapse property determines whether table borders are collapsed into a single border or separated into distinct borders.
• collapse: Borders are merged into a single border.
• separate: Borders are separated.
table {
border-collapse: collapse;
}
The padding property adds space inside the cells, between the cell content and the cell border. It improves readability by ensuring text doesn’t touch the cell border.
th, td {
padding: 10px;
}
The width property sets the width of the table or individual columns. It can be specified in pixels, percentages, or other units.
table {
width: 100%; /* Full width of the container */
}
td {
width: 25%; /* Each column takes up 25% of the table's width */
}
The height property sets the height of table rows or cells. It can help in controlling the vertical spacing within the table.
td {
height: 50px;
}
The text-align property specifies the horizontal alignment of text within table cells.
Values:
• left: Aligns text to the left.
• right: Aligns text to the right.
• center: Centers text.
th, td {
text-align: center;
}
The color property sets the text color within the table cells. This can be used to improve readability or to match a design scheme.
th {
color: white;
background-color: black;
}
The background-color property sets the background color of the table, rows, columns, or cells. This can help differentiate between header rows, data rows, or simply add aesthetic appeal.
tr:nth-child(even) {
background-color: #f2f2f2; /* Light grey for even rows */
}
<!DOCTYPE html>
<html>
<head>
<title>Styled Table</title>
<style>
table {
border-collapse: collapse;
width: 100%;
background-color: #f9f9f9;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
<tr>
<td>Data 4</td>
<td>Data 5</td>
<td>Data 6</td>
</tr>
</table>
</body>
</html>
| Header 1 | Header 2 | Header 3 |
|---|---|---|
| Data 1 | Data 2 | Data 3 |
| Data 4 | Data 5 | Data 6 |