CSS min() function to SASS

Viewed 4153

I have CSS function like below:

width: min(calc(100vw - 51rem), calc(100vh - 2rem));

It's working fine when using a CSS file but not when used in SASS. How can I rewrite this function for SASS?

3 Answers

When using SASS, min() is a function within SASS itself therefore your statement is not making it to your CSS when processed. There is a quick workaround since SASS is case sensitive and CSS is not. Simply capitalize the "M" in Min(). The Min() statement will not be recognized as the internal SASS min() function but will work in CSS.

    width: Min(calc(100vw - 51rem), calc(100vh - 2rem));

You can wrap min in a calc and it works:

width: calc(min(calc(100vw - 51rem), calc(100vh - 2rem)));

In your case you can even simplify the code:

width: calc(min(100vw - 51rem, 100vh - 2rem));

You can use these Sass functions to force the CSS functions.

@function css-function( $function, $values... ) {
    @return 
        $function
        + unquote( '(' )
        + $values
        + unquote( ')' )
    ;
}

@function css-min( $values... ) {
    @return css-function( min, $values );
}

@function css-max( $values... ) {
    @return css-function( max, $values );
}

@function css-clamp( $values... ) {
    @return css-function( clamp, $values );
}

You might still need to use #{ } interpolation when using Sass variables and CSS variables combined.

Usage:

$width-first: 40px;
$width-second: 30px;

.my-selector {
    width: css-min(#{$width-first}, #{$width-second});
}

Compiled:

.my-selector {
    width: min(40px, 30px);
}
Related