csspseudo-class

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


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!


Solution

  • 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>