小编典典

如何用另一种样式扩展CSS类?

css

我有近30个课程,我想将此课程应用于我的button元素。我不想为每个按钮元素添加class属性。有没有办法创建新的按钮类?

.button{
        .rounded-corner
        .corner
        .button-effective
        //another 20 classes
}

阅读 333

收藏
2020-05-16

共1个答案

小编典典

您将必须使用CSS预处理器来执行此操作。

萨斯

.rounded-corner {}
.corner {}
.button-effective {}

.button {
  @extend .rounded-corner;
  @extend .corner;
  @extend .button-effective
  // Continue with other classes.
}

编译为:

.rounded-corner, .button {}
.corner, .button {}
.button-effective, .button {}

**混合

@mixin rounded-corner {}
@mixin corner {}
@mixin button-effective {}

.button {
  @include .rounded-corner;
  @include .corner;
  @include .button-effective
  // Continue with other classes.
}

编译为:

.button {
  /* rounded-corner styles here */
  /* corner styles here */
  /* button-effective styles here */
}

LESS具有与SASS类似的共生关系,并且具有 扩展混合功能
,但是如果您想将一个类的样式添加到另一个类中,则LESS会更宽容一些。尽管我认为LESS中仍然考虑使用mixin,但您可以将一种类样式添加到另一种类样式中,如下所示,而不必使用关键字。

.rounded-corner {}
.corner {}
.button-effective {}

.button {
  .rounded-corner;
  .corner;
  .button-effective;
  // Continue with other classes.
}

编译为:

.button {
  /* rounded-corner styles here */
  /* corner styles here */
  /* button-effective styles here */
}
2020-05-16