Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

less - How to re-use a mixin whose selector is formed using concatenation

In Less, I can write:

.outer {  
    .inner {  
        color: red;  
    }  
}

.test {  
    .outer .inner;
}

But when I write:

.outer {  
    &-inner {  
        color: red;  
    }  
}

.test {  
    .outer-inner;
}

When I remove the .test, the .outer-inner output properly, but when I add it back, the compiler says

.outer-inner is undefined.

Is there anyway to re-use the styles of .outer-inner?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling a mixin whose selector is formed by concatenation is currently not possible with Less. However the same is possible for selectors formed at compilation time using interpolation (also referred to as dynamically formed selectors).

The below (interpolated/dynamically formed selector) would work fine.

@selector: .box;
@{selector}{
    color: red;
    .child{
        color:blue;
    }
}
.demo{
    .box; /* will create both parent & child */
}
.container{
? ? &.box{
    ? ? background: black;
    }
}
.demo2{
? ? .container.box;
}

whereas, the following example will not work.

.container{
    &-box{
        color: blue;
    }
}
.demo2{
    .container-box; /* this will not work */
}

Currently, one work-around to the scenario in question is to create two separate Less files.

In the first file (test.less) add the below code and compile it into a CSS file.

.outer {  
    &-inner {  
        color: red;  
    }  
}

In the second file, import the CSS created from the first file with the (less) directive and then call/re-use the mixin.

@import (less) "test.css";
.test {  
    .outer-inner;
}

Note: As mentioned in comments by seven-phases-max, this issue is similar to this item. However both these issues are not the same as extend will not work with both interpolated selector (dynamically formed) and concatenated selector.


Option 2: Another option would be to write a dummy mixin or a separate detached ruleset with common properties and make use of it like below.

@dummy: {color: red}; // detached ruleset

.outer{
    &-inner{
        @dummy();
    }
}

.test{
    @dummy();
}

or

.dummy() {color: blue}; // dummy mixin and would produce no extra selector in output as it has parentheses.

.outer{
    &-inner{
        .dummy;
    }
}

.test{
    .dummy;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...