csssass

How to use sass variables in css attribute selectors like [class^="$variables"]?


@mixin fullwidth($breakpoint,$grid-size)
{
    $varGridsize:col-#{$grid-size};
    @media only screen and (max-width: #{$breakpoint}px) { 
        [class ^="$varGridsize"]{width:100%;}
    }
}

how can we addd a variable in this [class ^="$varGridsize"] selector it is treating it as a string and returning a string in css file as

[class^="$varGridsize"] {
    width: 100%;
}

Solution

  • Simply interpolate $varGridsize using the #{} syntax:

    @mixin fullwidth($breakpoint, $grid-size) {
        $varGridsize: col-#{$grid-size};
    
        @media only screen and (max-width: #{$breakpoint}px) { 
           [class ^="#{$varGridsize}"] { width: 100% }
        }
    }