Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass BEM: avoid modifier duplication when element is inside a modifier

Tags:

sass

bem

Can I somehow refactor the following code snippet to get rid of double modifier declaration?

.block {
  &__element {
    rule: value;
  }
  &--modifier {
    rule: value;
  }
  &--modifier & {
    &__element {
      rule: value;
    }
  }
}

Output wanted:

.block {
   property: value;
}
.block--modifier {
  property: value;
}
.block--modifier .block__element {
  property: value;
}
like image 491
Yan Takushevich Avatar asked Aug 17 '15 14:08

Yan Takushevich


3 Answers

Nesting elements inside modifiers is a known issue. There are a lot of workarounds.

Variable way

Store the block element in a variable.

And use it interpolated when creating a element inside a modifier.

.block {
  $block: &;

  &__element {
    property: value;
  }

  &--modifier {
    property: value;
    #{$block}__element {
      property: value;
    }
  }
}

See output below.

Function way

1. Create a function that returns the block element.

It'll get the parent selector and cut the word before -- (which is the block). Looks hacky, but it's the simplest way to go.

@function block() {
  $selector: str-slice(inspect(&), 2, -2);
  $index: str-index($selector, '--') - 1;
  @return str-slice($selector, 0, $index);
}

2. Use the function interpolated.

Which will return the name of the block so you don't have to repeat it.

.block {
  property: value;

   &--modifier {
     property: value;
     #{block()}__element {
       property: value;
     }
   }
}

See output below.

Both ways will output to:

.block {
  property: value;
}

.block--modifier {
  property: value;
}

.block--modifier .block__element {
  property: value;
}
like image 140
Diéssica Avatar answered Oct 16 '22 00:10

Diéssica


You can place the block within the &--modifier selector like this, using the class name of the block rather than & to target it.

.block {
  &__element {
    rule: value;
  }
  &--modifier {
    rule: value;

    .block {
      &__element {
        rule: value;
      }
    }
  }
}

However, this is possibly not the best BEM solution, you should consider renaming the nested block as an element of the containing block, such as .block__another-element or creating a new block entirely.

like image 1
Toni Leigh Avatar answered Oct 15 '22 23:10

Toni Leigh


You could add & alongside the modifier for a solution similar to Toni's.

.block {

  &__element {
    rule: value;
  }

  &--modifier & {
    rule: value;
    
    &__element {
      rule: value;
    }
  }
}

This would however require .block to be a root selector and not nested inside any other selector.

Just another possible solution. For most situations though, I would still prefer Toni's solution.

like image 1
Mattias Larsson Avatar answered Oct 16 '22 00:10

Mattias Larsson