LESS使用伪选择器添加类

10

我使用LESS,以下是我的示例:

.arrow{
   color: red;
}
.arrow:before{
   content: ">";
}

.button{
  background: blue;
  .arrow;
  &:before{
    border: 1px solid;
  }
}

这是解析后的 CSS:

.button{
   background: blue;
   color: red;
}
.button:before{
   border: 1px solid; // HERE IS NO  content: ">" !!!
}

如何将.arrow类中的:before伪元素添加到我的按钮中?


为什么不使用 extend - Harry
3
如下的回答已经提到,您可以使用 extend ,但是针对您的代码片段存在的问题,如果您想将.arrow用作mixin,并且需要.arrow:before样式成为此mixin的一部分,则必须将.arrow:before嵌套在(任何).arrow {...} 定义中...(即.arrow可以作为mixin,但.arrow:before不能)。 - seven-phases-max
2个回答

19

您可以像下面这样使用extend选项。它基本上将arrow类的所有属性应用于button类。 all关键字表示子类也会被扩展。

LESS:

.button{
    background: blue;
    &:extend(.arrow all);
    &:before{
        border: 1px solid;
    }
}

编译后的 CSS:

.arrow,
.button {
    color: red;
}
.arrow:before,
.button:before {
    content: ">";
}

5
@Sergey Kudryashov,提醒一下,extend all也有其负面影响需要注意:如果你的代码中的其他地方也有.arrow样式,这个样式也会应用到你的.button上(例如#foo .bar.baz + div > p:hover.array {color: red}将把红色应用到你的按钮上)。 - seven-phases-max
@seven-phases-max 我猜你在例子中想说的是箭头而不是数组,对吗? - Davi Lima
@DaviLima 是的,那是一个打字错误。 - seven-phases-max

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接