Styling Alternate Table Rows Using :nth-child() in CSS
You can style alternate (even or odd) table rows using the :nth-child() pseudo-class in CSS. This method lets you apply alternating background colors or styles without adding extra classes to each row.
:nth-child(odd) targets all odd-numbered rows (1st, 3rd, 5th, etc.).
:nth-child(even) targets all even-numbered rows (2nd, 4th, 6th, etc.).
It works based on the element’s position among its siblings in the DOM.
In this example, the :nth-child(odd) selector applies a light gray background to odd rows, while :nth-child(even) adds a light blue shade to even rows, making the table easier to read.
Use alternating row colors to improve table readability.
Combine with hover effects (e.g., tr:hover) for better interactivity.
Use :nth-of-type() if your table contains mixed elements like tr and th siblings.
Avoid hard-coded colors that reduce accessibility contrast.
How would you style every other row in a static HTML table to have a light gray background without adding any classes or IDs?
What happens if you use nth-child(2n) instead of nth-child(even)? Does it behave the same, and why?
A table row background alternates correctly on initial load, but after filtering rows with JavaScript, the styling gets out of sync—how do you debug and fix this?
Your team’s table component uses inline styles for row colors, but the design system now requires alternating backgrounds. How would you refactor this without breaking existing functionality or requiring markup changes?
You’re optimizing a data-heavy table with 10,000+ rows that uses nth-child for alternating styles—how would you evaluate performance impact, and would you consider a different approach?
In a legacy app, alternating row styles are implemented with JS classes, but it’s causing reflows on every render. How would you migrate to pure CSS while maintaining accessibility and supporting older browsers?
You’re designing a cross-team table component library used across 50+ products—how do you ensure alternating row styling is maintainable, themeable, and doesn’t conflict with user-customized CSS or third-party plugins?
A legacy system uses inline styles for row alternation, and migrating to CSS selectors risks breaking analytics or accessibility tools that rely on class names. How would you architect a backward-compatible solution with zero-downtime rollout?