Joshua Frank Joshua Frank - 1 month ago 8
CSS Question

Is there a way to select an element AND siblings in css and/or less?

Often I want to style an element AND its younger siblings. Suppose I want to style the third

span
and all following ones. I know that I can do this:

span:nth-child(2) ~ span
{
width: 125px;
}


In English, this says "get the second
span
and style all following ones". So this effectively does style from the third one on.

But I don't like this syntax, because:


  • I have to read this carefully every single time, because it's not easy to understand.

  • If I change the HTML to use a
    div
    instead of a
    span
    , I have to change the corresponding CSS in two places.



So, is there any way, possibly using a LESS function or mixin, to do the equivalent of:

span:nth-child-or-following(3)
{
width: 125px;
}

Answer

Use span:nth-child(n + 3) { ... }

so there's no tag repetition and you would naturally use the index starting from 3

Codepen demo