Possible to reference extended property in less?

2019-07-21 15:04发布

Is it possible to extend a extended property in less? I have definitions in one (distributed) file and need to add !important to the existing property in my special case.

As example I have a less file defining this class

.pfx-grey-light-bg {
    background-color: #e5e5e7;
}

I'd like to reference this less file now but extend the color to important

.pfx-metro-orange-dark-bg:extend(.pfx-orange-dark-bg){
  //Pseudo code
  //background-color: &extended.backgroundColor !important
}

The result should be

.pfx-metro-grey-light-bg {
    background-color: #e5e5e7 !important;
}

标签: less
1条回答
一夜七次
2楼-- · 2019-07-21 15:38

No, you cannot extend a single property alone in that way. You can extend the whole ruleset but when you extend, the selectors are combined and so the !important would have to apply either to both the selectors or to none.

In your case the property values are different and hence the selectors cannot be grouped together. However, if the background-color is the only property within the original class that you wish to be applied to the derived class (or) if you wish to apply all properties of the original class to the derived class and append !important to all of them then you can use the below.

.pfx-grey-light-bg {
    background-color: #e5e5e7;
}

.pfx-metro-orange-dark-bg{
    .pfx-grey-light-bg !important;
}

When compiled, it would produce the following output:

.pfx-grey-light-bg {
    background-color: #e5e5e7;
}
.pfx-metro-orange-dark-bg {
    background-color: #e5e5e7 !important;
}

Or, if your base class has multiple properties and you want to apply only the background-color to the derived class, then you have three options as follows:

Option 1: Use variables

@color: #e5e5e7;

.pfx-grey-light-bg {
    background-color: @color;
    color: #fff;
}

.pfx-metro-orange-dark-bg{
    background-color: @color !important;

}

Option 2: Write a dummy mixin and use it like below. This will not cause any extra lines of code in the output CSS because the mixin has parentheses and hence will not be output.

.dummy-mixin(){
    background-color: #e5e5e7;
}
.pfx-grey-light-bg {
    .dummy-mixin;
    color: #fff;
}

.pfx-metro-orange-dark-bg{
    .dummy-mixin !important;
    padding: 10px;
}

Option 3: More complex using guarded mixins and an optional @important parameter to decide on whether to append !important or not. I would not recommend this unless you have very pressing needs.

.dummy-mixin(@color, @important: no){
    & when (@important = no){
        background-color: @color;
    }
    & when (@important = yes){
        background-cokor: @color !important;
    }
}
.pfx-grey-light-bg {
    .dummy-mixin(#e5e5e7);
    color: #fff;
}

.pfx-metro-orange-dark-bg{
    .dummy-mixin(#e5e5e7; yes);
    padding: 10px;
}
查看更多
登录 后发表回答