'defining a CSS background-color based on name

Knowing that you can define properties of an id/class like this

[id^="word-"]

But can you take that a step further and define the background-color based on the word that follows? For instance, if I called a bunch of classes: word-black, word-red, word-green, etc. Could I have one CSS class that finds the word after the "-" ie. black, red, green, etc.

Something like: [class^="word-"] {background-color = parsedClassName}



Solution 1:[1]

In my opinion that is impossible to do with pur css. But with Javascript you can do it.

example 1

const bgs = document.querySelectorAll('.dyn');
const r = document.querySelector(':root');

bgs.forEach(bg => {  
  const c = bg.classList[0].split('-')[1];
  bg.style.setProperty('--bg-color', c);  
})
:root {
   --bg-color: red;
}
div[class^="word-"] {
  background-color: var(--bg-color);
  color: white;
}
<div class="word-red dyn">hello</div>
<div class="word-green dyn">hello</div>
<div class="word-lightgreen dyn">hello</div>

example 2

const bgs = document.querySelectorAll('.dyn');
const r = document.querySelector(':root');

bgs.forEach(bg => {  
  const c = bg.classList[0].split('-')[1];  
  bg.style.backgroundColor = c;  
})
:root {
   --bg-color: red; /* default bg*/
}
div[class^="word-"] {
  background-color: var(--bg-color);
  color: white;
}
<div class="word-red dyn">hello</div>
<div class="word-green dyn">hello</div>
<div class="word-lightgreen dyn">hello</div>

Solution 2:[2]

The answer is yes and no.

Yes. If you are familiar with bootstrap, it is easily to change the text color using css classes like text-primary, text-danger, text-info. All you need to do is to import the bootstrap stylesheet.

No. When any of text colors you want is not being included from bootstrap color stylesheet, we have to write several css classes in stylesheets one by one, step by step (should not be done in JavaScript since it is not an interactive case).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 mondayrris