Focused selector in variable . How to do that stuf

2019-08-07 04:14发布

In SCSS i can do so: and then

$selector-active: "&:hover, &:focus, &:active";
.class {
    color: red;
    #{$selector-active} {
        color: green;
    }
}

And its working. How can i do this in LESS?

标签: css less
3条回答
何必那么认真
2楼-- · 2019-08-07 04:39

Hmm, interesting. Currently LESS does not expand its "&" within a selector interpolation, i.e. the straight-forward conversion DOES NOT work:

@selector-active: &:hover, &:focus, &:active;
.class {
    color: red;
    @{selector-active} {
        color: green;
    }
}

So you'll need some more tricky code... Using a callback/hook technique for example:

.selector-active() {
    &:hover, &:focus, &:active {
        .selector-active-properties();
    }
}

.class {
    color: red;
    .selector-active();
    .selector-active-properties() {
        color: green;
    }
}
查看更多
神经病院院长
3楼-- · 2019-08-07 04:44

You can get it even shorter:

.selector-active() {&:hover, &:focus, &:active {.-}}

.class {
    color: red;
    .selector-active;.-() {
        color: green;
    }
}

However there's important thing to remember when using hackish names for a hook/callback mixins. If at some point you need another mixin with the same technique then you'll also need another name for its callback (not the one you used for .selector-active()). Otherwise you get into problems if you try to use both "utilities" in the same scope. More over if you define some .inside() or .-() in the global scope they will override those coming from within .class and the trick becomes broken...

In other words, using "long/descriptive/unique" hook/callback names are just "safer" in a long run.

Btw. there's also a shorter syntax for the "hover specialization":

// same as .selector-active(@arg) when (@arg = hover):
.selector-active(hover) {
    &:hover {
        .inside();
    }
}
查看更多
Emotional °昔
4楼-- · 2019-08-07 04:51

I liked @Max nice solution. And this give me a way to move further. So i did a tweek with words for my self.

.selector-active() {
    &:hover, &:focus, &:active {
        .inside();
    }
}
.selector-active(@type) when (@type = hover) {
    &:hover {
        .inside();
    }
}

In use:

.class {
    color: red;
    .selector-active(); .inside() {
        color: red;
    }
}

I also tried to work with classes. LESS is prety owkward in this stuff, in 1.4.1 i must use:

.smthElse(@string) {
    &.class-@{string}-small,
    &.class-@{string}-big,
    &.class-@{string}-tall {
        .inside();
    }
}

in 1.3.1 i must to use:

(~".myclass_@{index}") {...

@see http://lesscss.org/

Enough compact, and could be in use. So i can still work with LESS :) yey.

P.S.: All above is for less.js v1.4.1

查看更多
登录 后发表回答