Build one CSS rule with @each

I am looking for a way to build a single CSS rule using sysls parameters with sals parameters.

Let's say I want to create a mixin transitionthat takes goals as parameters for writing one CSS rule transition(other parameters, such as transition time, etc., are constant).

@mixin transition($targets...) {
    @each $t in $targets {
        // construct the rule target by target
    }
    // and then transition: $rule; or something similar
}

I want to call him like

.foo {
    @include transition(color, width);
}

and get

.foo {
    transition: color 100ms ease-out, width 100ms ease-out;
}

The problem is that I could not find a way to build a string by concatenating. Is this possible, or is there any other way to do this?

+4
source share
1 answer

Here is one way:

@mixin transition($targets...) {
    $items: "";
    @each $item in $targets {
        $i: index($targets, $item);
        @if $i == length($targets) {
          $items: $items + $item + " 100ms ease-out";
        }

        @else {
          $items: $items + $item + " 100ms ease-out, ";
        }
    }
    transition: unquote($items);
}

Codepen (see compiled css)

1) Set the variable to hold the string

$items: "";

2) In each iteration of the $ loop, everyone gets an index:

$i: index($targets, $item);

3) $items. , ,

@if $i == length($targets) {
  $items: $items + $item + " 100ms ease-out";
}

@else {
  $items: $items + $item + " 100ms ease-out, ";
}

4) , unquote

transition: unquote($items);

:

.foo {
    @include transition(color, width);
}

CSS:

.foo {
  transition: color 100ms ease-out, width 100ms ease-out;
}
+2

Source: https://habr.com/ru/post/1691917/


All Articles