2

Is there a more efficient way to write the following CSS in LESS format, or is this it?

li:first-child {
    border-right: solid 0.188em #da291c;
    padding: 0 2em 0 0;
}

li:first-child + li {
    padding: 0 0 0 2em;
}

li:first-child + li + li {
    padding: 0 2em 0 0;
    border-right: solid 0.188em #da291c;
    margin-left: 21%;
}

li:first-child + li + li + li {
    padding: 0 0 0 2em;
}      
2
  • You could further complicate it like this.
    – Harry
    Commented Apr 15, 2016 at 13:16
  • 1
    (continuation of previous comment) but I wouldn't recommend using either this or any Less & stuff. What you have is as short as Less (with selector grouping done) and is more readable than using the & stuff. I'd also recommend using nth-child if you aren't looking to support IE8.
    – Harry
    Commented Apr 15, 2016 at 13:19

1 Answer 1

7

You can use & to refer to the parent selector:

li:first-child {
    border-right: solid 0.188em #da291c;
    padding: 0 2em 0 0;

    & + li {
        padding: 0 0 0 2em;

        & + li {
            padding: 0 2em 0 0;
            border-right: solid 0.188em #da291c;
            margin-left: 21%;

            & + li {
                padding: 0 0 0 2em;
            }
        }
    }
}

You could also use :nth-child, it might be more appropriate for what you are trying to do, but check browser support http://caniuse.com

1
  • 1
    Just FYI, in the case of the adjacent sibling selector, you don't actually need the &, just + [selector] will do Commented Apr 15, 2016 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.