We can apply style on HTML tables for better look and feel. There are some CSS properties that are widely used in designing table using CSS:
- border
- border-collapse
- padding
- width
- height
- text-align
- color
- background-color
CSS Table Border
We can apply borders to tables, th, and td elements by utilizing the CSS border attribute.
<style>
table, th, td {
border: 1px solid black;
}
</style>
Output:
| First_Name | Last_Name | Marks |
|---|---|---|
| Sonoo | Jaiswal | 60 |
| James | William | 80 |
| Swati | Sironi | 82 |
| Chetna | Abdul | 72 |
CSS Table Border Collapse
By utilizing the border-collapse property, it is possible to merge all borders into a single border.
<style>
table, th, td {
border: 2px solid black;
border-collapse: collapse;
}
</style>
Output:
| Name | Last Name | Marks |
|---|---|---|
| Sonoo | Jaiswal | 60 |
| James | William | 80 |
| Swati | Sironi | 82 |
| Chetna | Abdul | 72 |
CSS Table Padding
We have the ability to define padding for both the header and data cells within a table by utilizing the CSS padding attribute.
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 10px;
}
</style>
Output:
| Name | Last Name | Marks |
|---|---|---|
| Sonoo | Jaiswal | 60 |
| James | William | 80 |
| Swati | Sironi | 82 |
| Chetna | Abdul | 72 |
CSS Table: Styling even and odd cells
We have the option to enhance the appearance of alternating table cells for a more visually appealing design. Within this code snippet, we showcase distinct background colors for both even and odd cells. Additionally, we've modified the background-color and text color of the <th> element.
CSS code:
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 10px;
}
table#alter tr:nth-child(even) {
background-color: #eee;
}
table#alter tr:nth-child(odd) {
background-color: #fff;
}
table#alter th {
color: white;
background-color: gray;
}
</style>
Output: