ydoow
ydoow

Reputation: 2996

Dynamically assign a CSS class from within CSS

Is it possible to dynamically assign a class to an existing class? I am trying to allocate a style to the first child like this:

.active {
  color: red;
}

item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
  /* make it active class */
}

Upvotes: 4

Views: 99

Answers (1)

Stephan Muller
Stephan Muller

Reputation: 27600

No, this is simply not possible with just CSS.

The best you could do:

.active,
item:first-child .item_text {
  color: red;
}

item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
}

It is possible if you used a CSS preprocessor like LESS or SASS, which among others extend CSS with functionality like including/extending classes.

In LESS

item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
  .active;
}

This would literally replace that classname with the color: red; line.

In SASS (from version 3, which uses the "SCSS" syntax):

item:first-child .item_text {
  background: rgba(255, 255, 255, 1);
  @extend .active;
}

This would render the same output as my CSS example above.

Upvotes: 3

Related Questions