lavirius
lavirius

Reputation: 487

Using :extend() in LESS with pseudo-elements

I would like to code a simple alert component that has color variations as well as font icon variations. The icons are coded with :before. I can write it fine in in vanilla CSS but I want to do it in LESS as compact as possible and I am stuck with using :extend() which I rarely used :(

.base-alert {
    color: red;
    ...
    &:before {
        content: 'base-icon-unicode';
        ...
    }
}

In vanilla CSS the code for the variation classes would be like:

.alert-warning {
    color: red;
}
.alert-warning:before {
    content "warning-icon-unicode";
}

But then the HTML should be class="base-alert alert-warning". I would like to code the variation classes in LESS, using :extend() so in HTML I would only write class="alert-warning" or class="alert-succes" and so on. Something like:

.alert-warning {
    &:extend(.base-alert);
    color: orange;
    &:before {
       content "warning-icon-unicode";
    }
}

But it the :before doesn't apply anymore.

Upvotes: 2

Views: 1964

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241198

It seems like you are looking for the following:

.alert-warning:extend(.base-alert all) {
  color: orange;

  &:before {
    content: "warning-icon-unicode";
  }
}

This basically just extends .alert-warning from .base-alert using the all keyword. Then the content value for the pseudo-element is changed to warning-icon-unicode and the color is changed to orange.


Based on your comment about extending to multiple classes, I guess you could use the following, which will essentially just alias the selector:

.alert-warning, .alert-warning2 {
  &:extend(.base-alert all);

  color: orange;

  &:before {
    content: "warning-icon-unicode";
  }
}

Alternatively, depending on your preferences, you could also use the following, which will produce the same desired results.

.alert-warning:extend(.base-alert all),
.alert-warning2:extend(.base-alert all) {
  color: orange;

  &:before {
    content: "warning-icon-unicode";
  }
}

..this will work the same as well:

.alert-warning:extend(.base-alert all) {
  color: orange;

  &:before {
    content: "warning-icon-unicode";
  }
}

.alert-warning2:extend(.alert-warning all) {}

Upvotes: 10

Related Questions