I have the following SASS files
_android.scss:
$width: 111px;
@import 'child';
.android .child {
@extend %child;
}
_ios.scss:
$width: 999px;
@import 'child';
.ios .child {
@extend %child;
}
_child.scss:
%child {
width: $width;
}
app.scss:
@import 'ios';
@import 'android';
Now when I run sass I get:
$> sass app.scss
.ios .child, .android .child {
width: 999px; }
.ios .child, .android .child {
width: 111px; }
Not really what I expected, which is
.ios .child {
width: 999px;
}
.android .child {
width: 111px;
}
What is it what I do wrong here ?
It's because
@extends
are processed as they are first found in the sass, with all the selectors in which they are used grouped together at that point (@extends
is a bit greedy) and you're including the@extends
placeholder twice.Let's step through what happens:
$width
and includes%child
$width
is set to a new value and%child
included again.@extends
is encountered all instances of it are grouped and output with the values in the placeholder.This is why when you look at the output you see the both selectors grouped and this group repeated twice with each of the
$width
values defined.What to do to fix it
A mixin is best here. When a mixin is encountered it is evaluated on the spot and the resulting property set is injected into the selector.
Now, let's step through the mixin example
PS in my mixin definition I use a default value of
1000px
, which would be used if@include width();
was called.