Victor
Victor

Reputation: 13378

Using array of classes in SASS

Using SASS/SCSS. I have the following:

body:not(.sessions):not(.registrations):not(.home):not(.posts.new) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

This is not readable at all. How do I refactor this by using an array of classes:

$full-page-classes: .sessions .registrations .home .posts.new

Upvotes: 2

Views: 721

Answers (1)

Tân
Tân

Reputation: 1

If I understand you mean correctly, you may want to use the array like this:

$full-page-classes: '.sessions', '.registrations', '.home', '.posts.new';

@each $page-class in $full-page-classes {
  body:not(#{$page-class}) {
    padding-top: 4.5rem;
    padding-bottom: 7rem;
  }
}

Output:

body:not(.sessions) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

body:not(.registrations) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

body:not(.home) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

body:not(.posts.new) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

You can try it on sassmeister


Update:

If you want to generate inline CSS, you can try this:

$full-page-classes: '.sessions', '.registrations', '.home', '.posts.new';

$temp: '';

@each $page-class in $full-page-classes {
  $temp: $temp + ':not(#{$page-class})';
}

@each $item in $temp {
  body#{$item} {
    padding-top: 4.5rem;
    padding-bottom: 7rem;
  }
}

Output:

body:not(.sessions):not(.registrations):not(.home):not(.posts.new) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

Update 2:

@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;
}

$full-page-classes: ' .sessions, .registrations, .home, .posts.new,';

@each $x in str-replace(str-replace($full-page-classes, ' ', ':not('), ',', ')') {
  body#{$x} {
    padding-top: 4.5rem;
    padding-bottom: 7rem;
  }
}

Reference: str-replace function

Upvotes: 1

Related Questions