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

喜你入骨 提交于 2019-12-13 00:45:11

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/31852586/interpolated-class-names-and-extend-in-less-for-bem-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!