Is it possible to add a parent selector in LESS?

为君一笑 提交于 2020-01-21 05:42:06

问题


My css is structured in components, each component is stand-alone.

example:

.menu {
  background: black;
}

The framework I'm using sometimes adds a class to the body-tag. For example for logged in users it would look like this:

<body class="loggedIn">
  <div class="menu"</div>
</body

I would like to keep the css structured inside each component. Is it possible to add a selector in less that is added before the parent? Something like:

.menu{
  %loggedIn{
    color: red
  }
}

should give loggedIn users a red menu.


回答1:


Unless I am completely missunderstanding you, and there is a possibility, then the ampersand-parent-selector is exactly what you need!

.menu{
  .loggedIn & {
    color: red
  }
}

Should result in

.loggedIn .menu {
  color: red
}



回答2:


You can reference the parent selector using &: http://lesscss.org/features/#parent-selectors-feature

LESS

.menu {
   background: black;
  .loggedIn & {
    color: red
  }
}

Will compile to CSS

.menu {
   background: black;
}
.loggedIn .menu {
    color: red
}


来源:https://stackoverflow.com/questions/27146022/is-it-possible-to-add-a-parent-selector-in-less

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