Styling HTML Tables with CSS
Introduction
CSS can be used to style HTML tables and make them visually appealing. Let's explore some ways to style tables.
The table selector applies styles to the table element. We set the width to 100% and collapse the table borders using border-collapse: collapse.
The th selector applies styles to the table header cells. We set the background color to a light gray (#f2f2f2), add a border, set padding, and align the text to the left.
The td selector applies styles to the table data cells. We set a border, padding, and a default background color.
The tr:nth-child(even) selector selects every even row in the table body and applies a different background color (#f9f9f9) to create alternating row colors.
The .highlight class is applied to a specific cell in the table body to give it a yellow background color.
The .center class and the .right class are applied to specific cells to align the text to the center and right, respectively.
- Applying CSS styles to tables
- You can apply CSS styles directly to the <table> element or use class or ID selectors to target specific tables. By manipulating CSS properties like background-color, color, font-size, and padding, you can customize the appearance of your tables.
- Changing table font styles
- To change the font styles within a table, you can target the <td>, <th>, or <caption> elements and apply CSS properties such as font-family, font-weight, and text-transform.
- Customizing table borders
- CSS provides various properties to customize table borders, such as border, border-width, border-color, and border-radius. By using these properties, you can create different border styles, including rounded corners.
- Adding hover effects
- You can enhance the interactivity of your tables by adding hover effects. By applying CSS styles to the <tr> or <td> elements within a table, you can change their background color or apply other visual effects when a user hovers over them.
The table selector sets the width of the table to 100% and collapses the table borders using border-collapse: collapse.
The th selector applies styles to the table header cells. We set the background color to a light gray (#f2f2f2), add a border, set padding, and align the text to the left.
The td selector applies styles to the table data cells. We set a border and padding for the cells.
The tr:nth-child(even) selector selects every even row in the table body and applies a different background color (#f9f9f9) to create alternating row colors for better readability.
The th selector sets the font family to Arial and the font weight to bold for table headers. The font size is set to 14 pixels.
The td selector sets the font family to Verdana, the font weight to normal, and the font size to 12 pixels for table data cells.
You can modify the font family, font weight, and font size values in the CSS to customize the font styles to your preference.