What is the most economical way to write this code?
.colHeaders div:nth-child(2),
.colHeaders div:nth-child(3),
.colHeaders div:nth-child(4),
.colHeaders div:nth-child(11),
.colHeaders div:nth-child(12),
.colHeaders div:nth-child(14),
.colHeaders div:nth-child(15),
.colHeaders div:nth-child(16) {background: lightgrey;}
And why can I tell nth-child to skip children at the start, but not the end, of my parent element?
For example:
.colHeaders div:nth-child (2,3,4,11,12,14,15,16) {background: lightgrey;}
.colHeaders div:nth-child (2-4,11-12,14-16) {background: lightgrey;}
.colHeaders div:nth-child (n+2,4) {background: lightgrey;}
.colHeaders div:nth-child (n+11,12) {background: lightgrey;}
.colHeaders div:nth-child (n+14,16) {background: lightgrey;}
2
Answers
From your statements, you want
You can "merge" selectors using
:is()
and target individual ranges withnth-child
andnth-last-child
.For ranges you can state these like "nth-child(n+X):nth-child(-n+Y)" where X is the first to be selected and Y the last.
Like so:
Of course there are many ways to write this, I’m sure someone can come up with something better. Naturally, adding a class to those items and targeting that would be optimal…and quicker, probably.
I think it’s easier to use the negation in this case: