Specifying a list of arbitrary children (no patter

2019-02-24 22:31发布

问题:

So I've now read enough about various funky nth-child and nth-of-type patterns to have the seventh son of the seventh son fly a space-ship backwards to Pluto and back. But I still haven't come across a way to simply provide a list of specific children in a concise way. It'd work like so:

td:nth-child(1,3,7,10) { text-align: center; ... }

The above syntax would obviously be mighty convenient for example when styling table cells. That something like this would exist, seems like a no-brainer to me. Of course I can always use:

td:nth-child(1), td:nth-child(3), td:nth-child(7), td:nth-child(10) { ... }

But that's just so much redundant repetition and clutter in my CSS. Particularly when I need to also have a class name specified before the td. Then it becomes as bloated as this, for example:

.study_references td:nth-child(1), .study_references td:nth-child(3), .study_references td:nth-child(7), .study_references td:nth-child(10) { ... }

I'd really like to have my CSS look a bit more elegant, concise, and readable. Is there really no way to provide a specific list of nth-s to the selector in one shot? (Not looking for a preprocessor fix.)

回答1:

Unfortunately there isn't. Neither Selectors 4 nor CSS Syntax 3 have extended the An+B notation to allow a list of such expressions as in your 1,3,7,10 example either, though I wonder if it may be worth suggesting as it seems pretty doable. In fact, I just went ahead and suggested this (I couldn't find any earlier proposals using either the mailing list search, or Google).

The closest to a solution that Selectors 4 offers is via the :matches() pseudo, which makes it so that the only bit you have to repeat is :nth-child(...):

.study_references td:matches(
  :nth-child(1), :nth-child(3), :nth-child(7), :nth-child(10)
) { ... }

But this is still far from ideal, and is not yet implemented anyway.

If you can suss out at least part of a pattern from most of the numeric indices you're looking for, you could modify this pattern as necessary using :not() and/or additional :nth-child()/:nth-last-child() and still pick up the right elements. See this answer of mine where I refactor [9, 11, n+12] into [n+9 except 10]. However this is likely more trouble than it's worth, and the resulting selector will almost always be far from elegant unless you get really lucky as I did above.



回答2:

When CSS lacks a feature, Sass can help. You can try a formula like this one in Sass. It's not the most elegant solution, but perhaps you can improve on it.

$children: 1,3,7,10;

@each $child in $children {
  td:nth-child(#{$child}) {
    ...
  }
}