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}
CodePudding user response:
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 >hello</div>
<div >hello</div>
<div >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 >hello</div>
<div >hello</div>
<div >hello</div>
CodePudding user response:
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).