Search code examples
cssmathmodulo

CSS: modulo-like behavior without modulo or stepped functions


The environment I'm working with doesn't support CSS functions like mod(), round() or rem(). abs() and sign() are also not supported. However, max(), min() and clamp() are supported.

What I need is a workaround to achieve the behavior of a function f(a,b) that does the following: If a < b, return a. If a >= b, return 0. So basically, I need something that works like min(a,b), except when a >= b, it returns 0 instead of b.

I'm only dealing with positive integers. It doesn't matter what negative numbers would do.

If I could use mod(), then I could simply do mod(min(a,b),b) to get what I want.


Solution

  • You can use clamp()

    .box {
       --a: 20px;
       --b: 40px;
       --f: clamp(0px,(var(--b) - var(--a))*1000,var(--a));
       /* 
         if a < b --> (b-a)*1000 a big positive value clamped to a
         if a > b --> (b-a)*1000 a negative value clamped to 0
        */
        
       width: var(--f);
       border:2px solid red;
       height: 50px;
       margin: 10px;
    }
    <div class="box"></div>
    
    <div class="box" style="--b: 10px"></div>

    If it's integer, remove the unit:

    .box {
       --a: 20;
       --b: 40;
       --f: clamp(0,(var(--b) - var(--a))*1000,var(--a));
       /* 
         if a < b --> (b-a)*1000 a big positive value clamped to a
         if a > b --> (b-a)*1000 a negative value clamped to 0
        */
        
       width: calc(var(--f)*1px);
       border:2px solid red;
       height: 50px;
       margin: 10px;
    }
    <div class="box"></div>
    
    <div class="box" style="--b: 10"></div>