본문 바로가기
css/scss

[scss] @at-root가 아닌 @mixin으로 최상위 부모에 클래스 추가하기

by by-choice 2022. 5. 4.
반응형

.parent.bold .child span { font-weight: bold }를 지정하고자 할 때 @at-root를 잘못 활용하는 경우가 있다.

.parent {
  .child {
    span {
      @at-root .bold & {
        font-weight: bold;
      }
    }
  }
}

위의 컴파일 결과물은 .bold .parent .child span { font-weight: bold } 이다.

@at-root를 이용하여 .parent에 .bold 클래스를 추가하고자 한다면 귀찮더라도 클래스명을 다 적어줘야 한다.

.parent {
  .child {
    span {
      @at-root .parent.bold .child span {
        font-weight: bold;
      }
    }
  }
}

그런데,

이를 간단히 해결해 주신 분이 계셨으니, Pantaley Stoyanov.

 

 

You really made my life easier, thank you so much!

 

1. mixin 선언

@mixin most-outer-selector($new-class) {
  $current-selector: &;
  $new-selector: [];

  @each $item in $current-selector {
    $first-item: nth($item, 1);

    $appended-item: $first-item + $new-class;

    $new-item: set-nth($item, 1, $appended-item);
    $new-selector: append($new-item, $new-selector);
  }

  @at-root #{$new-selector} {
    @content;
  }
}

2. include로 활용

.parent {
  .child {
    span {
      @include most-outer-selector('.bold') {
        font-weight: bold;
      }
    }
  }
}

 

Add class to the most outer selector using Sass mixin | pantaley.com

Write and maintain clean and scalable styles by adding CSS class or id to the most outer selector using Sass mixin

pantaley.com

 

반응형

댓글