Wojtek
Wojtek

Reputation: 455

Combining CSS descendant and class selectors

Is there a convenient way to combine descendant selectors for a class that doesn't clutter the space much?

For example, I have two rules:

.details-recommendations-table th:nth-child(1) { /*rule*/ }
.details-recommendations-table td:nth-child(1) { /*rule*/ }

as the rules are the same, and describe some td and th elements within a class, it would be handy to combine them into one. Currently, I have

.details-recommendations-table th:nth-child(1), .details-recommendations-table td:nth-child(1) { /*rule*/ }

but that just clutters the space by repeating the name of the parent class. Is there a neat way to combine these rules, something along the lines of:

.details-recommendations-table th:nth-child(1), td:nth-child(1) { /*rule*/ }

The above doesn't work as the td:nth-child(1) part propagates to other tables, i.e. it doesn't apply only to td elements within the .details-recommendations-table class, as intended.

Upvotes: 3

Views: 1548

Answers (3)

emerson.marini
emerson.marini

Reputation: 9348

I've tested and fixed it now, according to the comment left by BoltClock's a Unicorn:

.details-recommendations-table :not(tr):not(tbody):nth-child(1) { /* rule */ }

Demo: http://jsfiddle.net/Ym9Va/

Upvotes: 0

jazZRo
jazZRo

Reputation: 1608

This will select any first child right beneath the tr:

.details-recommendations-table tr>*:nth-child(1) { /*rule*/ }

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

Assuming your td and th elements are validly placed within a tr element, you can simply condense your selector to:

.details-recommendations-table tr :nth-child(1) { /*rule*/ }

If, however, you're wanting to pull the first of each type (regardless of which nth child they are), you can use:

.details-recommendations-table tr :nth-of-type(1) { /*rule*/ }

JSFiddle demo.

In both cases this assumes that your td and th elements have no children. If they do have children, you should introduce a child combinator (>):

.details-recommendations-table tr > :nth-of-type(1) { /*rule*/ }

Upvotes: 2

Related Questions