Как использовать родительский селектор в качестве суффикса с Sass - PullRequest
0 голосов
/ 05 сентября 2018

Я знаю, что

.bg {
    &-orange { background-color: $orange; }
    &-yellow { background-color: $yellow; }
    &-blue { background-color: $blue; }
    &-green { background-color: $green; }
}

превратится в

.bg-orange { background-color: $orange; }
.bg-yellow { background-color: $yellow; }
.bg-blue { background-color: $blue; }
.bg-green { background-color: $green; }

Но что, если я хочу, чтобы " bg " в конце?

.orange-bg { background-color: $orange; }
.yellow-bg { background-color: $yellow; }
.blue-bg { background-color: $blue; }
.green-bg { background-color: $green; }

Как я могу сделать это с SASS? Есть идеи?

Ответы [ 3 ]

0 голосов
/ 06 сентября 2018

Вы можете получить доступ к родительскому селектору, используя амперсанд в функциях и миксинах, не передавая его в качестве параметра.

Я бы, наверное, сделал что-то подобное (демо) :

@mixin pre($modifier) {
  $ampersand: & + '';

  $parents-list: simple-selectors(str-replace($ampersand, ' ', ''));

  $suffix: nth($parents-list, -1) + '';
  $suffix-type: str-slice($suffix, 1, 1);
  $suffix-name: str-slice($suffix, 2, -1);

  $ascendant-selectors: str-replace($ampersand, $suffix, '');
  $current-selector: '#{$suffix-type}#{$modifier}-#{$suffix-name}';

  @at-root {
     #{$ascendant-selectors}#{$current-selector} {
      @content;
    }
  }
}

Чтобы это работало, вам понадобится также функция замены строки ( от Hugo Giraudel ):

@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);
  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }
  @return $string;
}


Как это работает:

SCSS

.bg {
  color: red;

  @include pre(blue) {
    color: blue;
  }
}

выход

.bg {
  color: red;
}

.blue-bg {
  color: blue;
}


Варианты использования:

  • .foo
  • span.foo
  • span .foo
  • .foo .bar
  • .foo.bar

Вы также можете использовать ID s.

0 голосов
/ 06 сентября 2018

Более простое решение

-bg {

    @at-root #{selector-append(".orange", &)} {
        color:orange;
    }// Here's the solution:
    @at-root #{selector-append(".yellow", &)} {
        color:yellow;
    }// Here's the solution:
    @at-root #{selector-append(".blue", &)} {
        color:blue;
    }
    @at-root #{selector-append(".green", &)} {
        color:green;
    }
}

Скомпилируется в

.orange-bg {
  color: orange;
}
.yellow-bg {
  color: yellow;
}
.blue-bg {
  color: blue;
}
.green-bg {
  color: green;
}
0 голосов
/ 05 сентября 2018

Вот где Mixin стал вашим другом: CodePen

@mixin sassyExample($color, $attrib) {
  #{'.' + $color + '-' + $attrib} {
   background-color: unquote($color); 
  }
}

@include sassyExample('orange', 'bg');
@include sassyExample('red', 'bg');
@include sassyExample('yellow', 'bg');

Вы можете пойти круче, нанести на карту и зациклить свои цвета, чтобы назначить что угодно, или добавить параметр, чтобы поменять местами цвета / атрибуты и т. Д., Но это всего лишь быстрое подтверждение концепции. Приветствия:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...