如何嵌套Less class继承父样式?

How to nest Less class to inherit parent styles?

更少的代码:

.btn-default:hover {
    background-color: rgba(217, 217, 217, 0.65);
    background-clip: content-box;

    .btn-default:focus {
        outline: 2px solid #047a9c;
    }
}

我想在这里做的是 btn-default:focus 应该有悬停状态的背景颜色,但只有焦点状态应该有轮廓。所以输出 CSS 应该是:

 .btn-default:hover {
     background-color: rgba(217, 217, 217, 0.65);
     background-clip: content-box;
 }

 .btn-default:focus {
     background-color: rgba(217, 217, 217, 0.65);
     background-clip: content-box;
     outline: 2px solid #047a9c;
 }

我对 LESS 嵌套部分有点迷茫,这可以用 less 实现吗?这样我就不必复制代码了。

您只需要将伪 类 嵌套到主选择器中。在这种情况下 .btn-default.

它应该是这样的:

.btn-default {
  /* some code here */

  &:hover, &:focus {
    background-color: rgba(217, 217, 217, 0.65);
    background-clip: content-box;
  }

  &:focus {
    outline: 2px solid #047a9c;
  }
}

&字符具有"this"关键字的功能

从你原来的问题:

.btn-default:hover {
  background-color: rgba(217, 217, 217, 0.65);
  background-clip: content-box;

  .btn-default:focus {
    outline: 2px solid #047a9c;
  }
}

Less 这种方式行不通。尝试发音你的代码。您的代码在 CSS:

中会像这样
.btn-default:hover {
  background-color: rgba(217, 217, 217, 0.65);
  background-clip: content-box;
}

.btn-default:hover.btn-default:focus {
    outline: 2px solid #047a9c;
}

您必须将伪类 和伪元素嵌套到主选择器 (.btn-default)

如果你想让更多的选择器、伪元素或伪类具有相同的属性,你应该使用,,而不是嵌套在另一个中。


以下是一些有用的链接:

Less to CSS compiler

LESS CSS nesting classes

Pseudo classes