LESS parent selector for first parent

核能气质少年 提交于 2019-12-13 02:01:06

问题


From documentation about changing selector order we can see this example:

.header {
  .menu {
    border-radius: 5px;
    .no-borderradius & {
      background-image: url('images/button-background.png');
    }
  }
}

and result will be

.no-borderradius .header .menu {}

How to use parent-selector & to get selector .header .menu.no-borderradius without duplicating code:

ul {
    li {
        a {
            .active &,
            &:hover {
                 color: red;
            }
        }
    }
}

will provide CSS

.active ul li a {color: red;}

but required result is

ul li.active a {color: red;}

回答1:


You have put the & (parent selector) at the wrong place. It shouldn't be put after the selector, instead it should be before the .. Setting the & after the selector means the whole parent selector (from the topmost selector) will be appended at the end of the current selector instead of getting inserted before (which is what you need for .header .menu.no-borderradius or ul li.active.

.header {
  .menu {
    border-radius: 5px;
    &.no-borderradius { /* here & is equal to .header .menu */
      background-image: url('images/button-background.png');
    }
  }
}

ul {
  li {
    &.active, /* here & is equal to ul li */
    &:hover {
      color: red;
    }
  }
}

Regarding the update to the question - it is currently not possible to achieve ul li.active a using the below structure as parent selector means the entire chain of selectors till the current level and not just the immediate parent. There is no way to just pick the immediate parent.

ul {
  li {
    a {
      .active &,
      &:hover {
        color: red;
      }
    }
  }
}

The only option currently possible is to write it like below:

ul {
  li {
    &.active a,
    a:hover {
      color: red;
    }
  }
}

There is an open feature request for parent selectors to have targets but there is no decision on by when this would be done.



来源:https://stackoverflow.com/questions/36908818/less-parent-selector-for-first-parent

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