Explain Codes LogoExplain Codes Logo

Apply style to cells of first row

html
responsive-design
css-selectors
table-styles
Nikita BarsukovbyNikita Barsukov·Dec 2, 2024
TLDR

Directly target the first table row's cells with CSS :first-child pseudo-class for a concise style application:

tr:first-child > * { background-color: #ccc; }

This code empowers you to style every cell (<th> or <td>) in the table's first row with a grey background without adding additional HTML.

Selection precision with child selectors

To intensify the style specifications and target only the cells of the first row within tables with the .category_table class, we introduce child selectors (>). Child selectors only affect top-level elements, not nested ones:

/* CSS equivalent of "First child, make your bed!" */ .category_table > tr:first-child > th, .category_table > tr:first-child > td { vertical-align: top; /* Reach for the stars, kiddo! */ background-color: #FFD700; /* Golden glow, like your future! */ }

The :first-child pseudo-element targets any first child element, not just a specific type. So, both <th> and <td> will get the golden glow!

Diving into table anatomy: 'thead' and 'tbody'

Styling within 'thead'

If your table is equipped with <thead>, <tbody>, and <tfoot> tags, you need to refine your style targeting to these distinct sections:

/* "How much does a hipster weigh? One Instagram!" */ .category_table thead tr:first-child > th { background-color: #32CD32; /* Table header, now greener than vegan diet! */ }

Remember, thead helps define the block of rows that serve as the table's head. Targeting within it ensures accuracy in style application.

Avoiding table formatting pitfalls

Avoid non-specific selectors, like table thead tbody tr:first-child, as they don't make structural sense. Thead and tbody are sibling elements, not parent-child, which confuses CSS. Our advice? Keep selectors simple and direct.

Leveraging advanced selectors for granular control

For precise control over your styles, you need advanced selectors to impact specific cell types or to exclude nested tables.

Target specific cell types

For instance, you might want to style only heading cells (<th>) in the first row:

.category_table > tr:first-child > th { font-size: 1.2em; /* Bigger than your ex's mistakes */ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Oh, so stylish! */ }

Handle mixed cell types with ':first-of-type'

And, in tables with mixed cell types, target the first cell of a particular type, like this:

.category_table > tr:first-child > td:first-of-type { text-align: left; /* Your left, not mine! */ padding-left: 10px; /* Breathing room, because claustrophobia is real! */ }