Specifying a list of arbitrary children (no template) for nth-child and nth-of-type

So, I've now read enough about the various funky models nth-child

and nth-of-type

for the seventh son of the seventh son to fly in a spaceship back to Pluto and back. But I still haven't found a way to just provide a list of specific children in a concise manner. It will work like this:

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

      

The above syntax will obviously be very handy when, for example, styling table tables. Something like this will exist, it seems uninteresting 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 this is just redundant repetition and clutter in my CSS. Specifically when I need to also have the class name listed 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 would really like my CSS to look a little more graceful, concise, and readable. Isn't there a way to provide a specific list of nth selectors in one shot? (Don't look for a preprocessor fix.)

+3


source to share


2 answers


Unfortunately no. Neither Selectors 4 nor CSS 3 Syntax extended Notation + B to allow a list of expressions like your example 1,3,7,10

, although I'm wondering if it's worth suggesting as it seems pretty doable. In fact, I just went ahead and suggested this (I couldn't find any earlier suggestions using either a mailing list search or Google search).

The closest :matches()

thing to a solution that Selectors 4 suggests is an alias , 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 has not yet been implemented.

If you can deduce at least part of the pattern from most of the numeric indices you are looking for, you can change that pattern as needed with :not()

and / or additional :nth-child()

/ :nth-last-child()

and still pick up the correct elements. See this answer of mine where I refactor [9, 11, n + 12] to [n + 9 except 10]. However, this is most likely more of a problem than it is worth, and the resulting selector will almost always be far from elegant unless you are more fortunate than I did above.

+4


source


When CSS is lacking in functionality, Sass can help. You can try a formula like this one at Sass. This is 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}) {
    ...
  }
}

      

0


source







All Articles