How to use !important keyword in a mixin?
Asked Answered
F

2

9

I can't get Sass to output the !important keyword with a mixin, I've tried:

@include font-size($font-size-sml) !important;

And:

@include font-size($font-size-sml !important);

It always throws an error.

EDIT

I ended up with this which works fine:

@mixin font-size($font-size, $sledge-hammer: "") {
    font-size: $font-size #{$sledge-hammer};
    font-size: ($font-size / $base-font-size)+rem #{$sledge-hammer};
    line-height: ceil($font-size / $base-line-height) * ($base-line-height / $font-size);
}
Fishbowl answered 2/1, 2013 at 7:36 Comment(4)
What is the error you get?Woodhouse
We need to see the mixin you're calling, the problem lies there.Buyse
Here's the mixin: @mixin font-size($font-size) { font-size: $font-size; font-size: ($font-size / $base-font-size)*1rem; line-height: ceil($font-size / $base-line-height) * ($base-line-height / $font-size); }Fishbowl
@ChrisPearce if provided answer solved your issue please accept itHolsworth
H
9

You can't add !important to whole mixin in SASS (It is possible in LESS I think) like you're trying to do in first example.

Second example works for me (you can pass !important with a parameter), I mean, if you use $font-size-sml directly as a property value it works, so maybe check your syntax.

But if it's really not working for you, you can do something with flag, set a important_flag as a mixin parameter and then use if-else statement in mixin. Something like this:

@mixin large-text($prop, $is_imp: false) {
    @if $is_imp == false {
        font-size: $prop;
    } @else {
        font-size: $prop !important;
    }
}

Maybe it's not a glamorous way to do it, but it works ;-)

Holsworth answered 2/1, 2013 at 8:55 Comment(3)
I can't get the 2nd example working, I've just started writing Sass so I'm new to the syntax. I'd rather not use a mixin to apply !important as it seems overkill, I thought it would be fairly easy to be able to add it when calling a mixin?Fishbowl
in your code, you use $font-size to do simple math, like $font-size / $base-font-size. So you can pass as parameter $font-size-sml !important because it will look like $font-size-sml !important / $base-font-size which is wrongHolsworth
Not having much luck with it I'm afraid.Fishbowl
J
0

You can use the if(condition, when-true, when-false) function.

So the code will be simplest and compact:

@mixin large-text($size, $isImportant: false) {
    font-size: $size if($isImportant, !important, null);
}
Joon answered 16/11, 2022 at 11:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.