CSS Table Styling
CSS can make HTML tables more attractive by controlling borders, colors, spacing, alignment, hover effects, and sizes.
1. Basic Table Styling
<table> <tr> <th>Name</th> <th>Age</th> <th>City</th> </tr> <tr> <td>Ali</td> <td>20</td> <td>Abbottabad</td> </tr> <tr> <td>Ahmed</td> <td>22</td> <td>Islamabad</td> </tr> </table>
table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #333; padding: 10px; text-align: left; } th { background-color: #333; color: white; }
2. Add Zebra Stripes
tr:nth-child(even) { background-color: #f2f2f2; }
This gives alternate rows different colors.
3. Add Hover Effect
tr:hover { background-color: #ddd; }
4. Center the Table Content
th, td { text-align: center; }
You can also vertically align content:
th, td { vertical-align: middle; }
5. Rounded Table
table { width: 100%; border-collapse: separate; border-spacing: 0; border: 1px solid #ccc; border-radius: 10px; overflow: hidden; }
6. Complete Example
<table class="student-table"> <tr> <th>Name</th> <th>Age</th> <th>Grade</th> </tr> <tr> <td>Ali</td> <td>20</td> <td>A</td> </tr> <tr> <td>Ahmed</td> <td>21</td> <td>B</td> </tr> <tr> <td>Usman</td> <td>19</td> <td>A</td> </tr> </table>
.student-table { width: 80%; margin: 30px auto; border-collapse: collapse; font-family: Arial, sans-serif; } .student-table th { background-color: #2563eb; color: white; padding: 12px; text-align: center; } .student-table td { padding: 10px; border: 1px solid #ddd; text-align: center; } .student-table tr:nth-child(even) { background-color: #f5f5f5; } .student-table tr:hover { background-color: #dbeafe; }
Important CSS Properties for Tables
| Property | Purpose |
|---|---|
border | Adds borders |
border-collapse | Combines table borders |
border-spacing | Controls space between cells |
padding | Adds space inside cells |
text-align | Horizontal alignment |
vertical-align | Vertical alignment |
background-color | Sets background color |
width | Sets table/cell width |
height | Sets table/cell height |
:hover | Styles rows when the mouse is over them |
:nth-child() | Targets specific rows/cells |
Comments
Post a Comment