How to change pseudo class color to match the color of another class?

18 Views Asked by At

I have created a 'block' for a webpage that for example is called 'test-div'.

Test div also has an extra class added to it to change its background color ie.

test-div test-div-bg-bright-gold 
test-div test-div-bg-dark-blue

etc.

My test-div also has a pseudo class before to cut the top-left border and I need the colour of this to match whatever the bg class is that's applied. The before CSS looks like this -

test-div::before {
     content: '';
    position: absolute;
    top: 0; left: 0;
    border-top: 100px solid white;
    border-right: 100px solid var(--COLORTOMATCHTHEBGCLASSGOESHERE?);
    width: 0;
   }

I've been trying to figure out how I can do this for ages, so any help would be greatly appreciated.

Thanks!

2

There are 2 best solutions below

0
disinfor On BEST ANSWER

You can set the var value inside of the color modification class. That way the variable can be applied to the background-color of the div and the border of the pseudo element.

.test-div {
  width: 200px;
  height: 300px;
  position: relative;
  background: var(--background-color);
}

.test-div--blue {
  --background-color: blue;
}

.test-div--gold {
  --background-color: gold;
}

.test-div::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  border-top: 100px solid white;
  border-right: 100px solid var(--background-color);
  width: 0;
}
<div class="test-div test-div--blue">
</div>

<div class="test-div test-div--gold">
</div>

0
Noleli On

CSS custom properties (aka variables) are inherited properties, so you can do it like this:

.card {
  --card-bg-color: white;
  background-color: var(--card-bg-color);
  padding: 8px;
  border: 1px solid gray;
  margin-block: 100px;
  position: relative;
}

.card::before {
  content: "";
  position: absolute;
  top: 0; left: 0;
  border-top: 100px solid white;
  border-right: 100px solid var(--card-bg-color);
  width: 0;
}

.card.error {
  --card-bg-color: red;
}
<div class="card"></div>
<div class="card error"></div>

When you override the value of the custom property, it’ll get inherited by its children (including pseudoelements).