Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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}

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!