프로그래밍/CSS & Sass

Sass(Scss)의 기능 - nesting

정구미 2023. 9. 9. 15:47

📌 Sass(Scss)의 nesting기능

기존 css로 작업할때 html구조가 복잡해지거나 많으면 모든 선택자를 중복해서 입력해야 하는 경우가 있는데,

Sass(Scss)의 nesting(중첩)기능을 이용하면 css를 구조화시킬 수 있어 효율적으로 작성할 수 있다.

 

👆 nesting 문법

선택자 안에 또 다른 선택자를 넣으면 된다.

🔗 Sass 공식페이지에 보면 예시와 함께 더 자세히 나와있다.

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

 

CSS

div {
  background: #fff;
}

div h2 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

div p {
  font-size: 14px;
  color: #777;
}

SCSS

div {
  background: #fff;  
  h2 {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }  
  p {
    font-size: 14px;
    color: #777;
  }
}

상위 요소인 div를 여러번 반복해서 입력하지 않고, div안에 하위 요소 스타일을 바로 입력한 것을 볼 수 있다.

 

✌️ 부모 요소 셀렉터 (Parent Selector)

& 기호는 중첩 내부에서 부모 요소를 의미한다.

 

CSS

.btn {
  background: #eee;
  color: #333;
}

.btn:hover {
  background: #000;
  color: #fff;
}

SCSS

.btn {
  background: #eee;
  color: #333;
  
  &:hover {
    background: #000;
    color: #fff;
  }
}