Styling Tables with CSS
While HTML provides attributes like border, cellpadding, and cellspacing, modern practice is to use CSS for styling tables. CSS makes tables more visually appealing, responsive, and user-friendly.
Basic Table Styling
Example:
<style>
table {
width: 70%;
border-collapse: collapse; /* Merges borders */
margin: 20px auto; /* Centers table */
}
th, td {
border: 1px solid #333;
padding: 10px;
text-align: center;
}
th {
background-color: #4CAF50;
color: white;
}
</style>
<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>London</td>
</tr>
</table>Output :

-
border-collapse: collapse;→ Removes double borders. -
padding: 10px;→ Space inside cells. -
margin: auto;→ Centers table.
Alternating Row Colors (Zebra Stripes)
Helps improve readability in large tables.
Example:
<style>
tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>Every even row gets a light background.
Hover Effects
Highlight rows when the user moves the mouse over them.
Example:
<style>
tr:hover {
background-color: #ddd;
cursor: pointer;
}
</style>Responsive Tables
Tables don’t always fit on small screens. You can make them scrollable:
Example:
<style>
.table-container {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
</style>
<div class="table-container">
<table>
<tr>
<th>Product</th>
<th>Price</th>
<th>Stock</th>
<th>Supplier</th>
<th>Location</th>
</tr>
<tr>
<td>Laptop</td>
<td>$800</td>
<td>10</td>
<td>ABC Corp</td>
<td>USA</td>
</tr>
<tr>
<td>Phone</td>
<td>$500</td>
<td>20</td>
<td>XYZ Ltd</td>
<td>UK</td>
</tr>
</table>
</div>The table becomes scrollable horizontally on small screens.
Output :

Advanced Styling (Full Example)
<style>
table {
width: 80%;
border-collapse: collapse;
margin: 20px auto;
font-family: Arial, sans-serif;
font-size: 16px;
}
th, td {
border: 1px solid #444;
padding: 12px;
text-align: center;
}
th {
background-color: #333;
color: white;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #d1e7dd;
transition: 0.3s;
}
caption {
font-size: 18px;
font-weight: bold;
margin: 10px;
}
</style>
<table>
<caption>Student Marks Table</caption>
<tr>
<th>Name</th>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>John</td>
<td>Math</td>
<td>85</td>
</tr>
<tr>
<td>Emma</td>
<td>Science</td>
<td>90</td>
</tr>
<tr>
<td>Raj</td>
<td>English</td>
<td>78</td>
</tr>
</table>Output :

