Forem

owieczka
owieczka

Posted on

CSS Equivalent of the "if" statement

Sometimes there is a need to select between two values based on some condition in css styling. One can uses simple two classes or javascript two select right stiling. But thanks to css variables if statements can be done also in pure CSS.

To select between two values in pure CSS you can use folowing math trick

Pseudocod:

if( valueSel < th) 
  return valueA
else
  return valueB
Enter fullscreen mode Exit fullscreen mode

This statement can be converted to folowing pseudocod:

selector = (sign(valueSel-th)+1)/2
return valueA * (1-selector) + valueB * selector
Enter fullscreen mode Exit fullscreen mode

Which can be expresed with help of css variables as:

CSS:

.some-class {
  --valueSel: /* Some Value - predicate */;
  --th: /* Some Treshold */;
  --valueA: /* Result A */;
  --valueB: /* Result B */;
  --selector: calc(clamp(0,tan( clamp(-1,var(--valueSel) - th, 1) ),1));
  --result: calc( var(--valueA) * (1 - var(--selector) ) + var(--valueB) * var(--selector) );    
}
Enter fullscreen mode Exit fullscreen mode

The selection can be extended to selecting colors via mix-color

You can see usage if this in Pure CSS radiational progress bar
https://codepen.io/owcakw/pen/KKEGvgZ

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay