CSS-Less 类使用伪类扩展类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9152989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:50:40  来源:igfitidea点击:

CSS-Less class extend class with pseudo class

cssmixinslesspseudo-class

提问by panosru

I was wondering how I could do something like the following with less css:

我想知道如何用更少的 css 做以下类似的事情:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.btn-foo {
  .btn;
  &:hover {
    .btn:hover;
  }
}

Of-course this is just an example, what need to point is if there is any way to extend the pseudo-class in order to avoid re-type the properties of :hoverpseudo class everywhere I need them. I know I could create a mixin for that but I'm wondering if I could avoid it.

当然这只是一个例子,需要指出的是是否有任何方法可以扩展伪类以避免:hover在我需要的地方重新输入伪类的属性。我知道我可以为此创建一个 mixin,但我想知道我是否可以避免它。

Thanks

谢谢

回答by bzx

UPDATE: If you can't modify external files just redefine the selectors, and add missing states:

更新:如果您不能修改外部文件,只需重新定义选择器,并添加缺少的状态:

.btn {
  // not adding anything here, won't affect existing style
  &:hover {
    // adding my own hover state for .btn
    background: yellow;
    ...
  }
}

// this will make your foo button appear as in external style
// and have the :hover state just as you defined it above
.btn-foo {
  .btn;
}

Better now? :)

现在好多了?:)



You don't need pseudo class. It will just work :)

你不需要伪类。它只会工作:)

Try this:

尝试这个:

.btn {
  background: yellow;

  &:hover { // define hover state here
    background: green;
  }
}

button {
  .btn;
}

Each <button class='btn'>element you create will inherit whatever was defined, including hover state. I think it's one of the main amazing features of LESS.

<button class='btn'>您创建的每个元素都将继承定义的内容,包括悬停状态。我认为这是 LESS 的主要惊人功能之一。

Hope this helps.

希望这可以帮助。

回答by John

In Less 1.4.0(1.4.1?)

在小于 1.4.0(1.4.1?)

This:

这个:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.btn-foo:extend(.btn all) { 
}

Expands to this:

扩展到这个:

.btn,
.btn-foo {
  color: black;
}
.btn:hover,
.btn-foo:hover {
  color: white;
}

Be cautious though, this:

不过要小心,这个:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.abc .btn {
  margin: 2px;
}

.btn-foo:extend(.btn all) {

}

Will output this:

将输出这个:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.abc .btn {
  margin: 2px;
}

.btn-foo:extend(.btn all) {

}

I have not looked into SASS more than half an hour, but I believe the later case is its default (or only) @extend behavior.

我没有研究 SASS 超过半小时,但我相信后一种情况是它的默认(或唯一)@extend 行为。