I have a Mixin like this:
@mixin column($fraction: null) {
// ...do stuff with $fraction
}
It can be used like so:
@include column('1/3');
Please note:
This works (used str-index + str-slice).
Now I'd like to make the quotes optional.
Meaning, this also needs to work:
@include column(1/3); // no quotes
Sass treats this as a number. Thats fine.
But it always does a division before I can do anything with the variable .
Include:
@include column(1/3);
Mixin:
@mixin column($fraction: null) {
$myVar: $fraction // $fraction equals '0.3333333' at this point already
}
Is there a way to prevent Sass from doing that? Or another way to get the denominator?
Thanks!
About using a Comma instead of Slash
As proposed by @Johannes Reuter I could just use a comma instead of a slash:
@include column(1,3);
Unfortunately means that the include looses a bit of meaning.
With a "1/3" it's clear that the column will be one third in width. I'd like to keep that.
It especially gets confusing with more parameters:
@include column(1, 3, 3, stacking);
vs
@include column(1/3, 3, stacking);
But thanks a lot for this answer.
You could pass the numerator and the denominator as two separate parameters:
Include:
@include column(1,3);
Mixin:
@mixin column($numerator: null, $denominator: null) {
//...
}
This would be much cleaner than string-operations.
Is a dirty trick but if you use argument list you get the value without division, then you have to convert in to string for extract the second value with str-slice
:
SASS
@mixin column($fraction...) {
$fraction: $fraction + "";
$n:str-slice($fraction, 3);
&:nth-child(#{$n}){
display:block;
}
}
.class{
@include column(1/3);
}
OUTPUT
.class:nth-child(3) {
display: block;
}
PS: The problem is if you want to use more parameters. I don't know how to solve it.
I found a way to do with two mixins, one with a list of parameters and the css properties and another one with variable arguments where I extract the number after division operator.
Variable arguments prevents doing the division but all the parameter go together and if I extract the 1st parameter the division doing again. Using two diferent mixins I can use the variable arguments and at the same time maintain separate parameters:
SASS
@mixin column2($col, $gutter) { width: $col * 100%; padding: $gutter; } @mixin column($args...) { $args-str: inspect($args); $separator: str-index($args-str, ","); $separator2: str-index($args-str, "/"); $fraction: str-slice($args-str, 1, $separator - 1); $cols: unquote(str-slice($fraction, $separator2 + 1)); &:nth-child(#{$cols}){ @include column2($args...); } } .class { @include column(1/3, 3px); }
OUTPUT
.class:nth-child(3) { width: 33.33333%; padding: 3px; }
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.