Zuno
Zuno

Reputation: 13

Is there any way to @extend sass placeholder properties into a single selector?

I have something like this

$colors: (primary: red, secondary: blue);
$font-sizes: (small: 14px, large: 64px);

@each $size, $value in $font-sizes {

  .font-#{$size} {
    font-size: $value;
  }

  %font-#{$size} {
    font-size: $value;
  }
}

@each $color, $value in $colors {

  .font-#{$color} {
    color: $value;
  }

  %font-#{$color} {
    color: $value;
  }
}

.custom-component-using-utility-classes {
  @extend %font-primary, %font-small;
}

It outputs this

.custom-component-using-utility-classes {
  color: red;
}

.custom-component-using-utility-classes {
  font-size: 14px;
}

But I want this

.custom-component-using-utility-classes {
    color: red;
    font-size: 14px;
}

How can I merge the placeholder properties to a single selector, instead of being separated like in the example above?

Pretty much like tailwindcss @apply, where it takes properties from classes.

Example

.my-component {
  @apply .py-2 .bg-red .mt-5
}

I tried using mixins but I don't want to make a mixin for every utility class, because I'm using maps and I generate them, so I want something similar with the example above.

Upvotes: 1

Views: 491

Answers (1)

mfluehr
mfluehr

Reputation: 3187

You can't do what you want by using placeholders. By definition, placeholders stay where they are in the original code, and you can't move them around or combine them.

To avoid creating a separate mixin for each value, create mixins that take a variable. (Do this outside of your @each loops.)

SCSS:

$colors: (primary: red, secondary: blue);
$font-sizes: (small: 14px, large: 64px);

@each $size, $value in $font-sizes {
  .font-#{$size} {
    font-size: $value;
  }
}

@each $color, $value in $colors {
  .font-#{$color} {
    color: $value;
  }
}

@mixin color($color) {
  font-size: map-get($colors, $color);
}

@mixin font-size($size) {
  font-size: map-get($font-sizes, $size);
}

.custom-component-using-utility-classes {
  @include color(primary);
  @include font-size(small);
}

Compiled CSS:

.font-small {
  font-size: 14px;
}

.font-large {
  font-size: 64px;
}

.font-primary {
  color: red;
}

.font-secondary {
  color: blue;
}

.custom-component-using-utility-classes {
  font-size: red;
  font-size: 14px;
}

Upvotes: 1

Related Questions