프로그래밍/Sass

[Sass/SCSS] 문법 - 중첩

미냐님 2020. 3. 26. 23:24
728x90

Sass(SCSS) 문법 - 중첩

  • Sass는 중첩 기능을 사용할 수 있습니다.
  • 상위 선택자의 반복을 피하고 좀 더 편리하게 복잡한 구조를 작성할 수 있습니다.
  • SCSS:
.section {
  width: 100%;
  .list {
    padding: 20px;
    li {
      float: left;
    }
  }
}
  • Compiled to:
.section {
  width: 100%;
}
.section .list {
  padding: 20px;
}
.section .list li {
  float: left;
}

Ampersand (상위 선택자 참조)

  • 중첩 안에서 & 키워드는 상위(부모) 선택자를 참조하여 치환합니다.

  • SCSS:

.btn {
  position: absolute;
  &.active {
    color: red;
  }
}

.list {
  li {
    &:last-child {
      margin-right: 0;
    }
  }
}
  • Compiled to:
.btn {
  position: absolute;
}
.btn.active {
  color: red;
}
.list li:last-child {
  margin-right: 0;
}
  • &키워드가 참조한 상위 선택자로 치환되는 것이기 때문에 다음과 같이 응용할 수도 있습니다.

  • SCSS:

.fs {
  &-small { font-size: 12px; }
  &-medium { font-size: 14px; }
  &-large { font-size: 16px; 
}
  • Compiled to:
.fs-small {
  font-size: 12px;
}
.fs-medium {
  font-size: 14px;
}
.fs-large {
  font-size: 16px;
}

@at-root (중첩 벗어나기)

  • 중첩에서 벗어나고 싶을 때 @at-root 키워드를 사용합니다.

  • 중첩 안에서 생성하되 중첩 밖에서 사용해야 경우에 유용합니다.

  • SCSS:

.list {
  $w: 100px;
  $h: 50px;
  li {
    width: $w;
    height: $h;
  }
  @at-root .box {
  width: $w;
  height: $h;
  }
}
  • Compiled to:
.fs-small {
  font-size: 12px;
}
.fs-medium {
  font-size: 14px;
}
.fs-large {
  font-size: 16px;
}
  • Error code:
.list {
  $w: 100px;
  $h: 50px;
  li {
    width: $w;
    height: $h;
  }
}

// Error
.box {
  width: $w;
  height: $h;
}
  • .list 안에 있는 특정 변수를 범위 밖에서 사용할 수 없기 때문에, 위 예제 처럼 @at-root 키워드를 사용해야 합니다.

중첩된 속성

  • font-, margin- 등과 같이 동일한 네임 스페이스를 가지는 속성들을 다음과 같이 사용할 수 있습니다.

  • SCSS:

.box {
  font: {
    weight: bold;
    size: 10px;
    family: sans-serif;
  };
  margin: {
    top: 10px;
    left: 20px;
  };
  padding: {
    bottom: 40px;
    right: 30px;
  };
}
  • Compiled to:
.box {
  font-weight: bold;
  font-size: 10px;
  font-family: sans-serif;
  margin-top: 10px;
  margin-left: 20px;
  padding-bottom: 40px;
  padding-right: 30px;
}
728x90

'프로그래밍 > Sass' 카테고리의 다른 글

[Sass/SCSS] 가져오기(Import)  (0) 2020.03.26
[Sass/SCSS] 문법 - 변수(Variables)  (0) 2020.03.26
[Sass/SCSS] 문법 - 주석  (0) 2020.03.26
Sass(SCSS) 컴파일 방법  (0) 2020.03.26
[Sass/SCSS] Sass와 SCSS는 차이점  (0) 2020.03.26