Search code examples
variablessassmedia-queriesfractions

How to use max-aspect-ratio with Sass using fraction as a variable?


How can I use a fraction in a variable with SASS language ? This code works :

div{
    @media screen and  (max-aspect-ratio: 54/25) {
       width:100%;
    }
}

This code doesn't works ( it compiles, but $var seems to be equal 0 ):

$var: 54/25;

div{
    @media screen and  (max-aspect-ratio: $var) {
        width:100%;
    }
}

When I use mixin I get the same weird issue.

// THIS MIXIN IS WORKING
@mixin media-maxAspectRatio() {
    @media screen and (max-aspect-ratio: 54/25) {
        &{ @content; }
    }
}

$breakpoints: (
    "mobileWidth": 500px,
    "fraction": 54/25
);

// THIS MIXIN IS NOT WORKING calling "fraction" as $_key 
@mixin media-maxAspectRatio($_key) {
    @media screen and (max-aspect-ratio: map-get($breakpoints, $_key)) 
    {
        &{ @content; 
         }
    }
}

It's weird to seems to work with px values but with fraction I get this not working. Maybe it's the / character ? More generally what's the best way to use sass variables with media queries and specially max-aspect-ratio and min-aspect-ratio. Thank you.


Solution

  • You need to define the aspect ratio as a string, otherwise Sass will compile the expression as a mathematical opetation, printing 2.16 instead of 54/25. Sass will print it unquoted when compiled.

    $breakpoints: (
        "mobileWidth": 500px,
        "fraction": "54/25"
    );
    
    @mixin media-maxAspectRatio($_key) {
        @media screen and (max-aspect-ratio: map-get($breakpoints, $_key)) {
          @content; 
        }
    }
    

    Check the working example here