Andrew Hoffman
Andrew Hoffman

Reputation: 820

Is there a way to write custom selectors in LESS?

I'll give an example of what I'd like to do.

:all() {
    &, 
    &:link,
    &:visited,
    &:active,
    &:focus
}

The above is an imagining of a 'custom selector' that itself returns a selection of all pseudo-classes of an anchor tag, minus :hover.

I'd like to use it as a selector like so:

.menu {
    a.top-level:all, span {
        color: @dormant-grey;
    }
    a.top-level:hover {
        color: @off-black;
    }
}

And for it to generate:

.menu a.top-level,
.menu a.top-level:link,
.menu a.top-level:visited,
.menu a.top-level:active,
.menu a.top-level:focus,
.menu span {
    color: #686868;
}
.menu a.top-level:hover {
    color: #22282a;
}

So I hope I'm communicating clearly what the question is. Is there a way to reuse selections?

Note that this is different than passing styles into a mixin. Passing styles into a mixin, to achieve the same thing, would require repeating the styling. Once to pass into the mixin, and then again for all the other selections that the mixin does not handle. Its also what I'm doing now and I'm finding that it isn't worth using the mixin because I've had to repeat myself so many times that I'm just going to pull it out.

So I hope that is clear. I'm asking if there is a way to reuse a selection, not a style. If less can't do it, is there a language that can?

Upvotes: 4

Views: 295

Answers (1)

seven-phases-max
seven-phases-max

Reputation: 11820

(So to not leave this one w/o an answer - copying my comment above):

.all(@-) {
    &,
    &:link,
    &:visited,
    &:active,
    &:focus {
        @-();
    }
}

.menu {
    .span {
        color: red;
    }
    a.top-level {
        .all({.span});
        :hover {
            color: blue;
        }
    }
}

This obviously produces duplicated styles for .span and a.top-level family but as soon as you care and generate a minified CSS version --clean-css --clean-option=--advanced option will eliminate duplicated styles with love.

Upvotes: 3

Related Questions