SCSS(Sass)의 중첩 선택자 기능은 CSS를 더 구조적으로 작성할 수 있게 해주지만, & 연산자의 동작 방식을 정확히 이해하지 못하면 의도하지 않은 CSS가 생성될 수 있습니다. 이 글에서는 & 연산자의 올바른 사용법과 흔한 실수를 살펴보겠습니다.
& 연산자를 공백 없이 바로 붙여 사용하면 형제 관계의 선택자가 생성됩니다.
.test {
&.test1 {
width: 100px;
height: 100px;
background-color: black;
}
}컴파일 결과:
.test.test1 {
width: 100px;
height: 100px;
background-color: black;
}이는 class="test test1"처럼 두 클래스를 모두 가진 요소를 선택합니다.
& 없이 직접 중첩하면 부모-자식 관계의 선택자가 생성됩니다.
.test2 {
.test3 {
width: 100px;
height: 100px;
background-color: yellow;
}
}컴파일 결과:
.test2 .test3 {
width: 100px;
height: 100px;
background-color: yellow;
}이는 .test2 내부의 .test3 요소를 선택합니다.
& 다음에 공백을 넣으면 부모-자식 관계를 명시적으로 표현할 수 있습니다.
.test {
& .test1 {
color: red;
}
}컴파일 결과:
.test .test1 {
color: red;
}하지만 이 방식은 다음과 같은 이유로 권장되지 않습니다:
& 다음의 공백이 명확하지 않아 혼란을 초래할 수 있습니다.&를 굳이 사용할 필요가 없습니다.&는 주로 다음과 같은 경우에 사용합니다:
수식어 클래스 추가:
.button {
background-color: blue;
&.primary {
background-color: red;
}
&.disabled {
opacity: 0.5;
cursor: not-allowed;
}
}가상 클래스 선택자:
.link {
color: blue;
&:hover {
color: darkblue;
}
&:visited {
color: purple;
}
}가상 요소:
.card {
position: relative;
&::before {
content: '';
position: absolute;
}
&::after {
content: '';
position: absolute;
}
}부모-자식 관계를 나타낼 때는 & 없이 직접 중첩하는 것이 명확합니다:
.test {
.test1 {
color: red;
}
}이는 다음과 동일하게 컴파일됩니다:
.test .test1 {
color: red;
}.card {
padding: 20px;
&__header {
font-size: 24px;
font-weight: bold;
}
&__body {
margin-top: 16px;
}
&--featured {
border: 2px solid gold;
}
}컴파일 결과:
.card {
padding: 20px;
}
.card__header {
font-size: 24px;
font-weight: bold;
}
.card__body {
margin-top: 16px;
}
.card--featured {
border: 2px solid gold;
}.container {
width: 100%;
@media (min-width: 768px) {
width: 750px;
}
@media (min-width: 1024px) {
width: 970px;
}
}// [주의] 잘못된 사용
.parent {
&child {
color: red;
}
}
// 결과: .parentchild (의도하지 않음)// [권장] 올바른 사용
.parent {
.child {
color: red;
}
}
// 결과: .parent .child// [주의] 불필요한 사용
.parent {
& .child {
color: red;
}
}// [권장] 간결한 사용
.parent {
.child {
color: red;
}
}SCSS의 & 연산자는 강력한 도구이지만, 올바르게 사용해야 합니다:
&를 공백 없이 사용 (.parent { &.modifier { } })&:로 사용 (.link { &:hover { } })& 없이 직접 중첩 (.parent { .child { } })이러한 원칙을 따르면 가독성 높고 유지보수하기 쉬운 SCSS 코드를 작성할 수 있습니다.