CSS Table
CSS Table
CSS offers powerful methods for customizing the appearance of HTML tables. CSS allows you to create well-structured and visually appealing tables to display organized data. Below is an in-depth guide to styling HTML tables with CSS, including various customization techniques with example.
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 enables the customization of table elements, improving their visual appeal and user experience across devices.
Key CSS Properties for Tables
1. Table Layout
The table-layout property controls the table's layout.
auto(default): The table automatically resizes columns to fit the content within them.fixed: Columns can be set to equal widths or customized based on specific values.
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
Below is a complete example showcasing a well-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 create responsive tables, wrap them in a container with the overflow property.
.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 enhances the presentation of tabular data, improving readability and design. Utilizing properties like border, padding, background-color,ensures visually appealing and responsive tables.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand CSS Tutorial visually:
What You'll Learn:
- 📌 HTML Tables Tutorial with CSS Styling - Crash Course
- 📌 How to Design a Stunning Table Using CSS (Step-by-Step Tutorial)