카테고리 없음
SCSS 기본 문법
shuai
2025. 1. 9. 11:32
SCSS를 오랜만에 다시 살펴보았다. 저번에는 변수 정의 문법을 주로 사용했었는데, 이번에는 전체적으로 살펴본 이후 프로젝트에 적용해볼 예정이다.
1. 변수
SCSS에서는 $로 변수를 선언하며, 색상, 폰트, 크기 값 등을 재사용할 수 있다.
$primary-color: #2db400;
$font-size: 16px;
button {
color: $primary-color;
font-size: $font-size;
}
2. 중첩(Nesting)
SCSS는 CSS 선택자를 중첩으로 표현하여 가독성을 높인다.
.navbar {
background: #333;
ul {
list-style: none;
li {
display: inline-block;
a {
color: white;
text-decoration: none;
}
}
}
}
위의 코드는 아래와 같이 컴파일 된다.
.navbar {
background: #333;
}
.navbar ul {
list-style: none;
}
.navbar ul li {
display: inline-block;
}
.navbar ul li a {
color: white;
text-decoration: none;
}
또한, 중첩 속성, 즉, 비슷한 속성을 중첩해 가독성을 높일 수 있다. 이 문법이 잘 사용될 것 같다.
button {
font: {
size: 16px;
weight: bold;
}
border: {
width: 1px;
style: solid;
color: #ccc;
}
}
위의 코드는 아래와 같이 컴파일 된다.
button {
font-size: 16px;
font-weight: bold;
border-width: 1px;
border-style: solid;
border-color: #ccc;
}
3. 믹스인(Mixins)
반복되는 스타일을 재사용할 때 사용한다.
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.container {
@include flex-center;
height: 100vh;
}
4. 상속
스타일을 다른 선택자와 공유할 때 사용한다.
.button {
padding: 10px 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.primary-button {
@extend .button;
background-color: #2db400;
color: white;
}
5. 연산
SCSS는 산술 연산자를 지원하여 크기 값을 계산할 수 있다.
$base-padding: 10px;
.container {
padding: $base-padding * 2; // 20px
margin: $base-padding + 5px; // 15px
}
6. 조건문
@if와 @else를 사용하여 조건에 따라 스타일을 적용할 수 있다.
$theme: light;
body {
@if $theme == light {
background: white;
color: black;
} @else {
background: black;
color: white;
}
}
7. 반복문
@for, @each, @while 등을 사용해 반복적으로 스타일을 생성할 수 있다.
@for $i from 1 through 3 {
.item-#{$i} {
width: $i * 10px;
}
}
위의 코드는 아래와 같이 컴파일 된다.
.item-1 {
width: 10px;
}
.item-2 {
width: 20px;
}
.item-3 {
width: 30px;
}
8. 함수
SCSS에서 제공하는 내장 함수와 사용자 정의 함수를 사용할 수 있다.
- 내장 함수
.container {
color: lighten(#2db400, 20%); // 더 밝은 초록색
background: darken(#2db400, 10%); // 더 어두운 초록색
}
- 사용자 정의 함수
@function calculate-spacing($base, $multiplier) {
@return $base * $multiplier;
}
.container {
padding: calculate-spacing(10px, 2); // 20px
}
9. import
SCSS 파일을 나누어 관리할 수 있으며, @import를 사용해 다른 파일을 불러온다.
// _variables.scss
$primary-color: #2db400;
// styles.scss
@import 'variables';
body {
color: $primary-color;
}