Home > Blockchain >  How to do something based on CSS variable content?
How to do something based on CSS variable content?

Time:08-19

Let's say I have a CSS variable:

div {
  --test: "hey"
}

And I would like to check what is inside this variable and do something based on this.

For example:

if var(--test) == "Hi":
  margin-bottom: 1rem;
else:
  padding-bottom: 1rem;

CodePudding user response:

natively isn't possible, but with a css compiler you can!

I suggest you use SASS/SCSS for this:

enter image description here

CodePudding user response:

I would like to check what is inside this variable and do something based on this.

Yes, you can check the value of a CSS Custom Property natively using:

window.getComputedStyle(myDiv).getPropertyValue('--test')

Once you know the value of --test, you can either update one (or several) properties:

  • myDiv.style.setProperty('padding-bottom', '1rem');

or you can add a class which updates one property (or any number of properties) of myDiv:

  • myDiv.classList.add('increaseBottomPadding');

Working Example:

const divs = document.querySelectorAll('div');

divs.forEach((div) => {

  let testValue = window.getComputedStyle(div).getPropertyValue('--test');
  
  switch (testValue) {
    case ('rainbow1') : div.classList.add('background1'); break;
    case ('rainbow2') : div.classList.add('background2'); break;
    case ('rainbow3') : div.classList.add('background3'); break;
    case ('rainbow4') : div.classList.add('background4'); break;
  }
});
div {
  display: inline-block;
  float: left;
  width: 120px;
  height: 120px;
  margin-right: 12px;
  background-color: rgb(255, 0, 0);
  border: 8px solid rgba(255, 255, 255, 0.5);
  border-radius: 50%;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.5);
}

.div1 {
  --test: rainbow1;
}

.div2 {
  --test: rainbow2;
}

.div3 {
  --test: rainbow3;
}

.div4 {
  --test: rainbow4;
}

.background1 {
  background-color: rgb(255, 0, 0);
}


.background2 {
  background-color: rgb(255, 127, 0);
}


.background3 {
  background-color: rgb(255, 255, 0);
}


.background4 {
  background-color: rgb(0, 127, 0);
}
<div ></div>
<div ></div>
<div ></div>
<div ></div>

  • Related