Table Properties in CSS
Table Properties in CSS
CSS provides several properties specifically for styling HTML tables. These properties allow you to control the layout, borders, and other aspects of tables. Here’s a brief overview:
1. border-collapse
Specifies whether table borders should collapse into a single border or be separated.
Values:
collapse
(borders are collapsed into a single border)separate
(borders are separated)
table { border-collapse: collapse; }
2. border-spacing
Defines the space between borders of adjacent cells when
border-collapse
is set toseparate
.Values: Length (e.g.,
px
,em
).table { border-spacing: 10px; }
3. caption-side
- Specifies the placement of a table caption.
- Values:
top
(default)bottom
caption { caption-side: bottom; }
4. empty-cells
Specifies whether or not to display borders for empty cells.
Values:
show
(display borders for empty cells)hide
(do not display borders for empty cells)
table { empty-cells: hide; }
5. table-layout
Defines the algorithm used to lay out the table cells, rows, and columns.
Values:
auto
(default, browser determines column width)fixed
(table layout is fixed, column widths are set bywidth
)
table { table-layout: fixed; }
6. border
Sets the border around the table, table rows (
<tr>
), table headers (<th>
), and table data cells (<td>
).Values: Border-width, border-style, border-color.
table, th, td { border: 1px solid black; }
7. width
Sets the width of the table or individual table columns.
Values: Length (e.g.,
px
,em
), Percentage (%
).table { width: 100%; } th, td { width: 25%; }
8. text-align
Aligns text within table cells.
Values:
left
,right
,center
,justify
.th, td { text-align: center; }
9. vertical-align
Aligns content vertically within table cells.
Values:
top
,middle
,bottom
,baseline
,text-top
,text-bottom
.td { vertical-align: middle; }
10. border-color
Sets the color of the table borders.
Values: Color names, HEX codes, RGB values, etc.
table { border-color: #333; }
Example Usage
Here’s a complete example of how these properties might be used:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
caption {
caption-side: top;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}