How to dynamically change values of CSS variables ONLY in CSS? Is it possible?

1.2k Views Asked by At

What I mean is, for example, I want to change the value of variable --color_rgb every time I increase the counter. What line to add to make it happen?

:root {
  --color_rgb: 50;
}

body {
  counter-set: color 0;
}

p::before {
  counter-increment: color 40;
  content: "Section. " counter(color) " ";
}

p {
  padding: 20px 20px 20px 20px;
  background-color: rgba(calc(var(--color_rgb)/2), var(--color_rgb), calc(var(--color_rgb)*2), 0.8);
}

2

There are 2 best solutions below

0
Friday Candour On

if you want to change a css variable value for particular screensize the it would work with @media queries

@media screen and (max-width: 760px) {
  :root {
    --ball-width: calc(200px);
  }
}

it may work in animations but i haven't tried it out yet, so i think you should give it a try.

0
Seba On

No. Since counter() returns a string, and you cannot parse a string to a number in CSS. The only way to update your --color_rgb by the number of p elements you have is if you add a lot of

...    
   p:nth-child(20){
     --color-rgb: 60; 
   }
...