Table Borders and Styling
HTML tables can be enhanced with CSS to control their appearance, including borders, background colors, spacing, and more. In this section, we'll explore how to style tables to achieve the desired visual effect.
Border Collapse
By default, HTML tables have a border-collapse value of "separate," which means each cell has its own border. To create a cleaner, more seamless look, you can set the border-collapse property to "collapse." This merges adjacent cell borders.
/* Example CSS to collapse table borders */
table {
border-collapse: collapse;
}
Adding Borders
You can specify borders for table elements such as <table>
, <th>
, and <td>
using CSS properties like border, border-width, and border-color. For example:
/* Example CSS to add borders to table elements */
table {
border: 1px solid #ccc;
}
th, td {
border: 1px solid #ccc;
}
Styling Headers
You can apply different styles to table headers (<th>
) to make them visually distinct. For instance, changing background colors and font styles can make headers stand out.
/* Example CSS to style table headers */
th {
background-color: #0077b6;
color: #fff;
font-weight: bold;
}
Background Colors
Setting background colors for the entire table, rows, or cells is an effective way to improve visual appeal.
/* Example CSS for background colors */
table {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #e0e0e0;
}
td {
background-color: #f8f8f8;
}
Cell Padding and Spacing
Controlling the spacing between the content and cell borders can improve the overall appearance of the table. Use padding for content within cells and cellspacing for space between cells.
/* Example CSS for cell padding and spacing */
td {
padding: 8px;
}
table {
border-spacing: 10px;
}
Table Width and Alignment
To adjust the width of the table and its alignment within the parent container, you can use CSS properties like width and margin.
/* Example CSS for table width and alignment */
table {
width: 100%;
margin: 0 auto;
}
Hover Effects
Adding hover effects to tables can make them more interactive and user-friendly. For example, changing cell background colors when a user hovers over a row:
/* Example CSS for hover effects */
tr:hover {
background-color: #f5f5f5;
cursor: pointer;
}
In summary, styling HTML tables with CSS allows you to control their visual appearance, borders, spacing, and more. Whether you want a clean and minimalistic look or a highly stylized table, CSS gives you the tools to achieve the desired design for your web page.