Parent Selector nested inside &:hover

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 04:53:16

问题


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

.module-name {
 // styles go here
 &__sub-module-1 {
  //styles go here
 }
}

Now my problem is how to continue to use the parent selector for adding the module-name inside a nested :hover statement. E.g. on hover of sub-module-1 I want to change something in sub-module-2. Inside the &:hover statement, what does the parent selector refer to?

.module-name {
  &__sub-module1 {
   &:hover {
    &__sub-module2 {
     // on hover of .module-name__sub-module1 change something in .module-name__sub-module2
    }
   }
  }
}

If i write it like this it works, but it defeats the purpose of using the parent selector to automatically fill in the name of the module:

.module-name {
  &__sub-module1 {
   &:hover {
    .module-name__sub-module2 {
     // on hover of .module-name__sub-module1 change something in .module-name__sub-module2
    }
   }
  }
}

I hope I could adequately express my problem; any help is appreciated.


回答1:


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


来源:https://stackoverflow.com/questions/28186972/parent-selector-nested-inside-hover

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