Matt Rek
Matt Rek

Reputation: 1831

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

Upvotes: 0

Views: 2948

Answers (2)

Cody MacPixelface
Cody MacPixelface

Reputation: 1386

You can make your own functions that returns either true or false based on the unit you are checking for.

Kitty Giraudel wrote about advanced type checking in Sass some years ago, and made some useful snippets you could possibly re-use.

For example you can check if the value is a number with an em or px unit like this (remove one of them from index() if you want to check for a single unit):

@function is-em($value) {
  @return is-number($value) and index('em', 'px', unit($value)) != null;
}

@debug is-em(42em); // true
@debug is-em(42px); // true
@debug is-em(42vw); // false

Or if the value is a number with a % unit like this:

@function is-percentage($value) {
  @return is-number($value) and unit($value) == "%";
}

@debug is-percentage(42.1337%); // true
@debug is-percentage(42cm);     // false

Perhaps not as simple as the test examples in your question, but the only way I can think of to check for numbers and units like this.

Upvotes: 3

Ted Whitehead
Ted Whitehead

Reputation: 1826

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.

Upvotes: 4

Related Questions