SCSS + BEM style children structure when parent has modificator

后端 未结 3 1542
轻奢々
轻奢々 2021-01-06 07:59

Please is possible to set scss for element inside --rounded ? I do not wanna use .box__something, but I need to modify children that is depend on parent modifier

<         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-06 08:26

    If I understand your problem correctly, I feel your pain! As soon as you nest a nested property & changes to the parent.

    You can however cache the original class name as a variable like this:

    $box: box;
    
    .#{$box} {
        .#{$box}__something {
            background: blue;
        }
        .#{$box}--rounded {
            background: green;
    
            .#{$box}__something { // <<< Is some better selector?
                background: pink;
            }
        }
    }
    

    The only problem with the method above is that you end up with a larger volume of compiled CSS. This renders to:

    .box .box__something {
      background: blue;
    }
    .box .box--rounded {
      background: green;
    }
    .box .box--rounded .box__something {
      background: pink;
    }
    

    To reduce the size of the output you could combine & with the variable method like so:

    .box {
      $box: &;
        &__something {
            background: blue;
        }
        &--rounded {
            background: green;
    
            #{$box}__something {
                background: pink;
            }
        }
    }
    

    This renders to:

    .box__something {
      background: blue;
    }
    .box--rounded {
      background: green;
    }
    .box--rounded .box__something {
      background: pink;
    }
    

    That way you can change the class name in the variable and everything gets updated, I also think it reads a bit better.

提交回复
热议问题