How to extend css class with another style?

You will have to use a CSS preprocessor to do this.

SASS

placeholder

%rounded-corner {}
%corner {}
%button-effective {}

.button {
  @extend %rounded-corner;
  @extend %corner;
  @extend %button-effective;

  /* Some other styles. */
}

.box {
  @extend %rounded-corner;
}

Compiles to:

.button, .box {
  /* rounded-corner styles */
}

.button {
  /* corner styles here */
}

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

.button {
  /* Some other styles. */
}

/*
`.box` is NOT defined here because it only uses placeholders. So it
is placed where the placeholder is defined.
*/

Note: with placeholders, the CSS selector is added to wherever the placeholder is defined. Not where the selector is defined.

extend

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

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

Compiles to:

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

mixin

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

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

Compiles to:

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

LESS

LESS has a similar sytanx to SASS and also has extend and mixin, though LESS is a little more forgiving if you want to add one class’ style to another. While I believe still considered a mixin in LESS, you can add one class style to another like the following without having to use a keyword.

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

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

Compiles to:

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

Leave a Comment