본문 바로가기
Style Sheets/Sass(SCSS)

[SCSS] 스타일 규칙 - 중첩(Nesting)

by 썸머워즈 2022. 6. 22.
반응형

중첩 (Nesting)

기본적인 스타일 규칙은 CSS와 동일한 방식으로 작동하지만,

SCSS에서는 중첩 (Nesting) 기능을 사용해 상위 선택자의 반복을 피하고 좀 더 편리하게 구조를 작성할 수 있다.

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

to css

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}

중첩 기능은 매우 유용하지만 실제로 생성하는 css의 양을 시각화하기 어렵게 만들 수도 있다.

쉽게 말하면 중첩을 너무 깊게 사용하지 말라는 의미이다.

 

그래서 보통 3중첩을 넘어가는 경우 그 이후 중첩부터 새롭게 선언하여 다시 스타일링하는 방식을 사용한다.

 

상위 선택자 참조 (&)

부모 선택자를 참조 할때는 & 키워드를 사용한다.

.alert {
  /* The parent selector can be used to add pseudo-classes to the outer */
  /* selector. */
  &:hover {
    font-weight: bold;
  }

  /* It can also be used to style the outer selector in a certain context, such */
  /* as a body set to use a right-to-left language. */
  [dir=rtl] & {
    margin-left: 0;
    margin-right: 10px;
  }

  /* You can even use it as an argument to pseudo-class selectors. */
  :not(&) {
    opacity: 0.8;
  }
}

to css

.alert:hover {
  font-weight: bold;
}
[dir=rtl] .alert {
  margin-left: 0;
  margin-right: 10px;
}
:not(.alert) {
  opacity: 0.8;
}

여기서 & 키워드는 상위 선택자로 치환되는 것이기 때문에 다음과 같이 응용하여 사용할 수 있다.

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

to css

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

 

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

중첩 안에서 생성하지만 중첩 밖에서 사용해야 하는 경우 @at-root를 사용하여 해당 중첩을 벗어날 수 있다.

.list {
  $w: 100px;
  $h: 50px;
  li {
    width: $w;
    height: $h;
  }
  @at-root .box {
    width: $w;
    height: $h;
  }
}

to css

.list li {
  width: 100px;
  height: 50px;
}
.box {
  width: 100px;
  height: 50px;
}

보통 중첩내 특정 변수만 사용하고 밖으로 빠져나가고 싶을 때 사용한다.


참고: https://sass-lang.com/documentation/style-rules

 

Sass: Style Rules

Style rules are the foundation of Sass, just like they are for CSS. And they work the same way: you choose which elements to style with a selector, and declare properties that affect how those elements look. SCSS Syntax .button { padding: 3px 10px; font-s

sass-lang.com

참고: https://sass-lang.com/documentation/style-rules/parent-selector

 

Sass: Parent Selector

The parent selector, &, is a special selector invented by Sass that’s used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before

sass-lang.com

참고: https://heropy.blog/2018/01/31/sass/

 

Sass(SCSS) 완전 정복!

Style(CSS) 작업 시 필수가 되어버린 CSS Preprocessor(전처리기) Sass(SCSS)에 대해서 이해하고, CSS로 컴파일하는 방법부터 자세한 SCSS 문법까지 살펴봅니다.

heropy.blog

반응형


댓글

TOP