简体   繁体   中英

SCSS Mixin Error: expected a variable name (e.g. $x)

I get this error:

While processing files with fourseven:scss (for target web.browser):
   /client/stylesheets/main.scss: Scss compiler error: expected a variable name (e.g. $x)
   or ')' for the parameter list for pos-abs

This is my @mixin :

_mixins.scss:

@mixin pos-abs ($top, $right, $bottom, $left) {
  position: absolute;
  top: percentage($top + 'px' / $h);
  right: percentage($right + 'px' / $w);
  bottom: percentage($bottom + 'px' / $h);
  left: percentage($left + 'px' / $w);
};

This is how I call @mixin :

_foo.scss:

@mixin pos-abs(0, 313, 0, 12);

This is where I declared vars :

_sizes.scss:

$w: 375px;
$h: 662px;

This is my file load order:

main.scss:

@import "sizes";
@import "mixins";
@import "foo";

PS If I remove $h & $w vars and hardcode them in the @mixin (eg top: percentage($top + 'px' / 662px); ) -- I get the same error. If I remove all + 'px' from my @mixin and pass args to the mixin like: @mixin pos-abs(0px, 313px, 0px, 12px); -- the error persists.

Where is my mistake?

Problem 1:

The way you are calling the mixin seems to be wrong. The correct way would be to call it as follows:

@include [mixin-name]([mixin-params]);

When you write @mixin pos-abs... , the compiler seems to be expecting (and rightly so) a variable to follow the mixin name as that is a mixin definition statement and hence the error states that it expects a variable or a closing parenthesis to follow the opening parenthesis.


Problem 2:

Even after resolving that error, you'd still run into a problem with the percentage function. In that, you are appending the px via string concatenation to the number and this would make the whole value to be cast as a string instead of a number. This means any math operations on it would fail.

You should instead multiply the number with 1px or add 0px . This would not only add the units to the value but would also make it a number.

$w: 375px;
$h: 662px;

@mixin pos-abs ($top, $right, $bottom, $left) {
  position: absolute;
  top: percentage($top * 1px / $h);
  right: percentage($right * 1px / $w);
  bottom: percentage($bottom * 1px  / $h);
  left: percentage($left * 1px / $w);
};

#demo{
  @include pos-abs(0, 313, 0, 12);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM