如何用另一种风格扩展css类?

hel*_*one 13 css

我有近30个课程,我想将这些课程应用到我的按钮元素.我不想为每个按钮元素添加class属性.有没有办法创建一个新的按钮类,如;

.button{
        .rounded-corner
        .corner
        .button-effective
        //another 20 classes
}
Run Code Online (Sandbox Code Playgroud)

hun*_*tar 18

您将不得不使用CSS预处理器来执行此操作.

上海社会科学院

延伸

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

.button {
  @extend .rounded-corner;
  @extend .corner;
  @extend .button-effective
  // Continue with other classes.
}
Run Code Online (Sandbox Code Playgroud)

编译为:

.rounded-corner, .button {}
.corner, .button {}
.button-effective, .button {}
Run Code Online (Sandbox Code Playgroud)

混入

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

.button {
  @include .rounded-corner;
  @include .corner;
  @include .button-effective
  // Continue with other classes.
}
Run Code Online (Sandbox Code Playgroud)

编译为:

.button {
  /* rounded-corner styles here */
  /* corner styles here */
  /* button-effective styles here */
}
Run Code Online (Sandbox Code Playgroud)

LESS与SASS有类似的sytanx,也有扩展mixin,但如果你想将一个类的风格添加到另一个类,那么LESS会更宽容一些.虽然我认为仍然在LESS中考虑使用mixin,但您可以像下面这样添加一个类样式,而不必使用关键字.

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

.button {
  .rounded-corner;
  .corner;
  .button-effective;
  // Continue with other classes.
}
Run Code Online (Sandbox Code Playgroud)

编译为:

.button {
  /* rounded-corner styles here */
  /* corner styles here */
  /* button-effective styles here */
}
Run Code Online (Sandbox Code Playgroud)


Jay*_*ayx 8

您可以使用属性选择器并连接您的类;它仍然涉及向您的按钮元素添加一个长类:

<button class="button-rounded-corner-effective">Your button</button>
Run Code Online (Sandbox Code Playgroud)

或者

<button class="button rounded corner effective">Your button</button>
/* Which is exactly what you did not want to do,
   but the CSS below will apply all the same.
   This example to clarify, then. */
Run Code Online (Sandbox Code Playgroud)

...然后你的 CSS 将是:

[class*="button"]{/*Generic button styles*/}
[class*="rounded"]{/*Rounded styles*/}
[class*="corner"]{/*Corner styles*/}
[class*="effective"]{/*Effective styles*/}
Run Code Online (Sandbox Code Playgroud)

不过,您需要注意命名空间 - 通配符选择器将匹配具有匹配字符串的任何类。

例如:

[class*="round"]{/*Will match rounded*/}
Run Code Online (Sandbox Code Playgroud)


Mik*_*cer 7

通过CSS 模块,您可以使用composes

.className {
  color: green;
  background: red;
}

.otherClassName {
  composes: className;
  color: yellow;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

CSS4中有可能:

 :root {
  --toolbar-theme: {
    border-radius: 4px;
  };
  --toolbar-title-theme: {
    color: green;
  };
}

.toolbar {
  @apply --toolbar-theme;
  @apply --toolbar-title-theme;
}
Run Code Online (Sandbox Code Playgroud)

目前,您需要使用Sass/Less预处理器.

  • [没有 CSS4 这样的东西。永远不会有 CSS4](https://css-tricks.com/css4/)。 (5认同)
  • 这里说`@ apply`已被放弃:/ https://tabatkins.github.io/specs/css-apply-rule/ https://www.xanthir.com/b4o00 (2认同)