LESS: Extend a previously defined nested selector

谁说我不能喝 提交于 2019-11-28 07:51:45

问题


I've been trying like a mad man to get the following LESS statement to work, but now i am fearing that it's not gonna happen :/ So I am turning now to you guys in the end for help!

I have the following statement:

.top{
    &-first{
        background:black;
        &-item{
            color:white;
        }
    }
    &-second{
        background:green;
        &-item:extend(.top-first-item){}
    }
}

I was hoping for to achive the following output:

.top-first {
    background: black;
}
.top-first-item,
.top-second-item{
    color: white;
}
.top-second {
    background: green;
}

But unfortunately it does not compile that but this instead:

.top-first {
    background: black;
}
.top-first-item{
    color: white;
}
.top-second {
    background: green;
}

回答1:


LESS currently does not support extending a "concatenated name" selectors (basically, .top &-first &-item is interpreted as three distinct selector elements and never found by extend looking for a single selector).

A workaround for your particular case:

.top {
    &-first {
        background: black;
    }

    &-second {
        background: green;
    }

    &-first, &-second {
        &-item {
            color: white;
        }
    }
}



回答2:


Another option is to break the designations into separate classes:

LESS

.top{
    &.first{
        background:black;
        &.item{
            color:white;
        }
    }
    &.second{
        background:green;
        &.item:extend(.top.first.item){}
    }
}

CSS Output

.top.first {
  background: black;
}
.top.first.item,
.top.second.item {
  color: white;
}
.top.second {
  background: green;
}

Which of course requires a change in your html designation from class="top-first-item" to class="top first item".




回答3:


This is obviously something that should be working in LESS. I have a few months ago put an issue on the LESS.js github regarding exactly this.

Link to Github issue

In the mean time, i recommend using seven-phases-max's solution by simply putting the classes together like so:

&-first, &-second {}

But then you cant abstract the second out into another file.

Another solution would to make an "extends.less" file, in which you can have small snippets you find your self using time from time.




回答4:


Just use 'all' suffix. Example: &:extend(.top-first-item all);



来源:https://stackoverflow.com/questions/20091264/less-extend-a-previously-defined-nested-selector

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