Tables
CSS provides properties to style and customize HTML tables, allowing you to control the appearance, layout, and spacing of table elements. Let’s explore how to use CSS to style tables and make them visually appealing.
Table Borders
The border
property is used to set the border around the table and its cells. It allows you to define the border width, style, and color. Here’s an example:
table {
border: 1px solid #ccc;
}
td, th {
border: 1px solid #ccc;
}
Table Width and Height
The width
and height
properties control the dimensions of the table. You can set them to specific pixel values or use relative units like percentages. Here’s an example:
table {
width: 100%;
height: 300px;
}
Table Cell Padding and Spacing
The padding
property controls the space between the cell content and the cell border, while the border-spacing
property sets the space between adjacent cells. Here’s an example:
table {
padding: 10px;
border-spacing: 5px;
}
Table Header Styling
The th
element is used to define table headers. You can apply specific styles to table headers using CSS selectors. Here’s an example:
th {
background-color: #f0f0f0;
font-weight: bold;
}
Table Striping
You can use the:nth-child
selector to apply alternating styles to table rows, creating a striped effect. Here’s an example:
tr:nth-child(even) {
background-color: #f9f9f9;
}
Table Caption Styling
The caption
element is used to provide a title or caption for the table. You can style the caption using CSS properties. Here’s an example:
caption {
font-size: 18px;
font-weight: bold;
}
CSS properties related to tables:
Property | Description |
---|---|
border | Sets the border around the table and its cells. |
border-collapse | Specifies whether the table borders should be collapsed into a single border or separated. |
border-spacing | Sets the space between adjacent cells in the table. |
caption-side | Specifies the placement of the table caption. |
empty-cells | Controls the display of empty cells in the table. |
table-layout | Defines the algorithm used for laying out the table. |
width | Sets the width of the table. |
height | Sets the height of the table. |
text-align | Aligns the text within table cells horizontally. |
vertical-align | Aligns the content within table cells vertically. |
padding | Sets the space between the cell content and the cell border. |
background-color | Sets the background color of the table or table cells. |
color | Sets the text color within table cells. |
font-size | Sets the font size of the text within table cells. |
font-weight | Sets the font weight of the text within table cells. |
Conclusion
CSS provides a range of properties to style and customizes HTML tables. By using properties like border
, width
, height
, padding
, border-spacing
, and CSS selectors like th
and :nth-child
, you can create visually appealing and well-structured tables. Experiment with different styles and techniques to achieve the desired table layout and appearance on your web pages.