Search code examples
csssass

Check the kind of unit in Sass/SCSS to optimise CSS


I am trying to check whether the units are compatible and then either use calc() or just calculate them in pre-processing.

Is there any way of checking the unit type in Sass?

If I type:

//  SCSS

test {
  content: type-of(1px);
  content: type-of(1%);
  content: type-of(1em);
}

I get

/*  CSS  */

test  {
  content: number;
  content: number;
  content: number;
}

Is there a way of getting something more like:

 /*  CSS  */

test {
  content: px;
  content: percent;
  content: em;
}

It can potentially save a lot of unnecessary CSS that can be easily optimised in pre-processing.

For example when a @mixin or a @function can take either fixed or flexible units:

# flexible container needs calc()
width:calc(((100vw - (12vw + 242px)) / 12) * 6 + 110px)

# fixed main container 
width:calc(((2880px - (110px + 242px)) / 12) * 6 + 110px) 
# can be calculated in SASS and rendered simply as 
width:1374px

Solution

  • I think using calc() is fine, but you could get the units by multiplying the original value by 0, converting to a string, then removing the zero.

    @function getUnit($value) {
      @return str-slice($value * 0 + "", 2, -1);
    }
    

    Demo: https://www.sassmeister.com/gist/6ac692efdbb8a28be8a3cd4346b39970

    FYI, there’s also a unit() function but the docs warn that:

    “This function is intended for debugging; its output format is not guaranteed to be consistent across Sass versions or implementations.”

    https://sass-lang.com/documentation/modules/math#unit

    If that’s not a concern for your use case, then that would probably be the simplest way to go.