Styling HTML Tables with CSS: Zebra Stripes, Hover Effects, More

Enhance your HTML tables with visually appealing CSS styles. This tutorial demonstrates creating zebra stripes (horizontal and vertical), adding horizontal dividers, implementing hover effects, and combining these techniques for improved readability and user experience. Includes code examples!



Styling HTML Tables with CSS

This chapter demonstrates various CSS techniques to enhance the visual presentation of your HTML tables, adding visual interest and improving readability.

Zebra Stripes

A common table styling technique is creating "zebra stripes"—alternating row colors for better readability. This is achieved using the CSS :nth-child(even) selector.

Example: Horizontal Zebra Stripes

tr:nth-child(even) {
  background-color: #D6EEEE;
}

This applies a light blue background to every even-numbered row. Using :nth-child(odd) would style the odd-numbered rows instead.

Vertical Zebra Stripes

To create vertical zebra stripes, apply the styling to every other column instead of every other row. You need to target both <th> and <td> elements.

Example: Vertical Zebra Stripes

td:nth-child(even), th:nth-child(even) {
  background-color: #D6EEEE;
}

Combined Horizontal and Vertical Stripes

You can combine horizontal and vertical stripes. Using an rgba() color allows you to control the transparency (opacity) for an overlapping effect.

Example: Combined Stripes

tr:nth-child(even) {
  background-color: rgba(150, 212, 212, 0.4);
}
th:nth-child(even), td:nth-child(even) {
  background-color: rgba(150, 212, 212, 0.4);
}

Horizontal Dividers

To add horizontal dividers between rows, use the border-bottom property on each <tr> element.

Example: Horizontal Dividers

tr {
  border-bottom: 1px solid #ddd;
}

Hover Effect

A hover effect highlights rows when the mouse cursor passes over them. Use the :hover selector on the <tr> element.

Example: Hover Effect

tr:hover {
  background-color: #D6EEEE;
}