CSS Table
CSS Table
CSS (Cascading Style Sheets) provides robust options for styling HTML tables. Tables are often used to display tabular data, and CSS enhances their appearance and usability. Here's a detailed explanation of CSS tables with examples.
What is a CSS Table?
In web development, an HTML table organizes data into rows and columns using the <table>
, <tr>
(table row), <th>
(table header), and <td>
(table data) elements. CSS allows developers to style these elements for better readability, responsiveness, and aesthetics.
Key CSS Properties for Tables
1. Table Layout
The table-layout
property controls the table's layout.
auto
(default): The table adjusts column widths based on content.fixed
: Columns have equal widths or as specified.
table { table-layout: fixed; width: 100%; }
2. Border
Borders enhance table structure visibility. Use border
to style table edges.
table, th, td { border: 1px solid black; border-collapse: collapse; /* Prevent double borders */ }
3. Padding and Spacing
- Padding: Adds space inside cells.
- Spacing: Adjusts space between cells.
th, td { padding: 10px; text-align: center; /* Centers content */ }
4. Background and Colors
Background colors can improve readability.
th { background-color: #f2f2f2; color: #333; } tr:nth-child(even) { background-color: #f9f9f9; }
5. Hover Effects
Adding hover effects enhances interactivity.
tr:hover { background-color: #e0e0e0; }
CSS Table Example
Here’s a full example of a styled table:
HTML
<table> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td>Apple</td> <td>$1</td> <td>50</td> </tr> <tr> <td>Banana</td> <td>$0.5</td> <td>100</td> </tr> <tr> <td>Orange</td> <td>$0.8</td> <td>75</td> </tr> </tbody> </table>
CSS
table { width: 80%; margin: 20px auto; border-collapse: collapse; font-family: Arial, sans-serif; } th, td { border: 1px solid #ddd; padding: 12px; } th { background-color: #4CAF50; color: white; } tr:nth-child(even) { background-color: #f2f2f2; } tr:hover { background-color: #ddd; } td { text-align: center; }
Responsive Tables
To make tables responsive, use the overflow
property inside a parent container.
.table-container { overflow-x: auto; } table { width: 100%; border-collapse: collapse; }
HTML Example:
<div class="table-container"> <table> <!-- Table content here --> </table> </div>
Conclusion
CSS tables provide a powerful way to style tabular data, making it visually appealing and user-friendly. By using properties like border
, padding
, background-color
, and responsive techniques, you can create tables that look great across devices.