Parent Selector nested inside &:hover

前端 未结 1 1362
执念已碎
执念已碎 2020-12-07 05:01

I am using the Less parent selector to shorten my selectors:

.module-name {
 // styles go here
 &__sub-module-1 {
  //styles go here
 }
}
相关标签:
1条回答
  • 2020-12-07 05:49

    The parent selector (&) will always refer to the full parent based on the level at which you are. For example at the first level of nesting, & refers to .module-name. In the second level, it refers to .module-name__sub-module1 and in the third level, it refers to .module-name__sub-module1:hover.

    Extract from Less Website: Note that & represents all parent selectors (not just the nearest ancestor or the overall root ancestor)

    The emphasised part in the above statement is my inclusion based on the context

    For this particular case, you could assign the module-name to a variable and use selector interpolation like below to form the selectors.

    The variable value would never change unlike the parent selector (&) irrespective of how many levels of nesting you have and at which level of nesting you are using it.

    @module-name: mod-name;
    .@{module-name} {
        &__sub-module1 {
            &:hover {
                & .@{module-name}__sub-module2 {
                    // on hover of .module-name__sub-module1 change something in .module-name__sub-module2
                    color: blue;
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题