Reputation: 157
I would like to ask a question about mixin uage
My target is to change the font size of TESTING according to different language using mixin. The Home class and language class must be set in HTML tag.
<html class='Home en'>
<body>
<div class='text'>TESTING</div>
</body>
</html>
CSS setting
.Home {
.text {
@include font(20)
}
}
I wrote a mixin to handle font size according to different language
@mixin font($size) {
font-size: $size + px;
.en & {
font-size: $size - 5 + px;
}
}
However, the output will become: .en .Home .text { ... } instead of .en.Home .text { ... }
How can i handle this case using mixin? Or any other alternative can i used to fix this problem without changing the class in HTML tag?
Thanks all!
Upvotes: 0
Views: 660
Reputation: 4335
You need to parse the &
reference and use the first selector to concatenate with .en
and then get the rest of the selector to build the full selector. &
is a list of lists containing all the parent selectors, so you can iterate thru the list using Sass lists functions.
Try the following:
@mixin font($size) {
font-size: $size + px;
// Get the first parent selector, to aply the '.en'
$root: nth(nth(&, 1), 1);
// Get all the other parent selectors
$rest : ();
@for $i from 2 through length(nth(&, 1)) {
$rest: append($rest, nth(nth(&, 1), $i));
}
// Create the selector
$selector: unquote(".en#{$root} #{$rest}");
// Print it at root
@at-root #{$selector} {
font-size: $size - 5 + px;
}
}
Check the workimng code here
Upvotes: 3