CSS tables provide powerful tools for creating and styling tabular data on web pages. They offer greater flexibility and control compared to traditional HTML tables.
CSS tables allow developers to structure content in rows and columns without using HTML table elements. This approach, known as CSS table layout, offers several advantages:
To create a CSS table, use the display
property with table-related values:
.table {
display: table;
}
.table-row {
display: table-row;
}
.table-cell {
display: table-cell;
}
This CSS transforms regular div elements into table-like structures:
<div class="table">
<div class="table-row">
<div class="table-cell">Cell 1</div>
<div class="table-cell">Cell 2</div>
</div>
</div>
CSS provides various properties for styling tables:
border-collapse
: Controls border behaviorborder-spacing
: Sets space between cellscaption-side
: Positions the table captionempty-cells
: Defines how empty cells are displayed
.styled-table {
display: table;
border-collapse: collapse;
width: 100%;
}
.styled-row {
display: table-row;
}
.styled-cell {
display: table-cell;
padding: 10px;
border: 1px solid #ddd;
}
Creating responsive tables with CSS is crucial for mobile-friendly designs. One approach is to use CSS Media Queries to adjust table layout on smaller screens:
@media screen and (max-width: 600px) {
.table-row {
display: block;
margin-bottom: 10px;
}
.table-cell {
display: block;
border: none;
position: relative;
padding-left: 50%;
}
.table-cell:before {
content: attr(data-label);
position: absolute;
left: 6px;
width: 45%;
padding-right: 10px;
white-space: nowrap;
font-weight: bold;
}
}
This technique transforms the table into a vertical layout on smaller screens, improving readability.
By mastering CSS tables, you can create flexible, accessible, and visually appealing tabular layouts for your web projects.