Natan Felles
Natan Felles

Reputation: 1051

SCSS dynamic selectors

I have this SCSS code:

$box-length: 12 !default;
@for $i from 1 through $box-length {
  .box-#{$i} {
    flex: 0 0 (100% / $box-length * $i);
  }
}

Below, I need to add the generated .box-{num} classes with other selectors. To have a CSS result like this:

@media screen and (max-width: 768px) {
  .row,
  .column,
  .box,
  .box-1,
  .box-2,
  .box-3,
  .box-4,
  .box-5 {
    /* ... */
  }
}

How to append the dynamic .box-{num} classes to .row, .column, .box?

Thank you!

Upvotes: 5

Views: 751

Answers (1)

Arkellys
Arkellys

Reputation: 7801

1. Using a placeholder selector and @extend:

@media screen and (max-width: 768px) {
    %mq-768 {
        /* ... */
    }
}

.row,
.column,
.box {
  @extend %mq-768;
}

$box-length: 12 !default;
@for $i from 1 through $box-length {
  .box-#{$i} {
    @extend %mq-768;
    flex: 0 0 (100% / $box-length * $i);
  }
}

Compiles as:

@media screen and (max-width: 768px) {
  .box-12,
  .box-11,
  [...],
  .box-2,
  .box-1,
  .row,
  .column,
  .box {
    /* ... */
  }
}

.box-1 {
  flex: 0 0 8.3333333333%;
}

.box-2 {
  flex: 0 0 16.6666666667%;
}

[...]

.box-12 {
  flex: 0 0 100%;
}

2. Using a variable to store the selectors and append:

$selectors: ".row, .column, .box";

$box-length: 12 !default;
@for $i from 1 through $box-length {
    $boxSelector: ".box-#{$i}" ;
    $selectors: append($selectors, $boxSelector, $separator: comma);
    
  #{$boxSelector} {
    flex: 0 0 (100% / $box-length * $i);
  }
}

@media screen and (max-width: 768px) {
    #{$selectors} {
        color: blue;
    }
}

Compiles as:

.box-1 {
  flex: 0 0 8.3333333333%;
}

.box-2 {
  flex: 0 0 16.6666666667%;
}

[...]

.box-12 {
  flex: 0 0 100%;
}

@media screen and (max-width: 768px) {
  .row,
  .column,
  .box,
  .box-1,
  .box-2,
  [...],
  .box-11,
  .box-12 {
    /* ... */
  }
}

Upvotes: 2

Related Questions