Home Scss 문법 정리
Post
Cancel

Scss 문법 정리


목차

변수
중첩
같은 네임스페이스끼리 묶기
@mixin @include
@extend
@for
@each
@if
if
@function
& (Ampersand)
@at-root
#{} (문자 보간법)
!default
@import
@use
@content
파일 분할


변수

변수를 정의해서 사용할 수 있다.

1
$변수명: ;

변수의 유효범위 : 선언된 블록({}) 내에서만 유효범위를 가짐
변수 재할당 : 변수를 다른 변수에 다시 할당할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 SCSS 구문
$red: red;
$color-error: $red;  // 재할당1
.box1 {
    color: $color-error;
}
.box2 {
    $color-error: blue; // 재할당2
    color: $color-error;
}

 컴파일된 CSS 구문
.box1 {
    color: red;
}
.box2 {
    color: blue;
}

중첩

선택자를 중첩해서 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
 SCSS 구문
div {
    .active {
        color: red;
    }
}

 컴파일된 CSS 구문
div .active {
    color: red;
}

같은 네임스페이스끼리 묶기

스타일 속성 이름이 같은 것끼리 묶을 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 SCSS 구문
div {
    font: {
        size: 10px;
        weight: bold;
        family: Arial;
    }
    margin: {
        left: 0;
        right: 10px;
    }
}

 컴파일된 CSS 구문
div {
    font-size: 10px;
    font-weight: bold;
    font-family: Arial;
    margin-left: 0;
    margin-right: 10px;
}

@mixin @include

스타일 블록을 만들어 재사용할 수 있다.

기본 구문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 SCSS 구문
@mixin basic {
    margin: 0;
    padding: 0;
    background-color: white;
}

div {
    @include basic;
}

 컴파일된 CSS 구문
div {
    margin: 0;
    padding: 0;
    background-color: white;
}

매개변수 구문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 SCSS 구문
@mixin basic($color) {
    margin: 0;
    padding: 0;
    background-color: $color;
}

div {
    @include basic(white);
}

 컴파일된 CSS 구문
div {
    margin: 0;
    padding: 0;
    background-color: white;
}

매개변수에 기본값이 있는 구문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 SCSS 구문
@mixin basic($color: red) {
    margin: 0;
    padding: 0;
    background-color: $color;
}

.box1 {
    @include basic();
}
.box2 {
    @include basic(white);
}

 컴파일된 CSS 구문
.box1 {
    margin: 0;
    padding: 0;
    background-color: red;
}
.box2 {
    margin: 0;
    padding: 0;
    background-color: white;
}

매개변수에 키워드가 있는 구문

인수 입력 시 명시적으로 키워드 입력하여 작성
인수 순서 상관없이 작성할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 SCSS 구문
@mixin basic($color: red, $width, $height) {
    margin: 0;
    padding: 0;
    background-color: $color;
    width: $width;
    height: $height;
}

.box1 {
    @include basic($width: 100px, $height: 200px);
}

 컴파일된 CSS 구문
.box1 {
    margin: 0;
    padding: 0;
    background-color: red;
    width: 100px;
    height: 200px;
}

가변인수 사용

인수의 개수가 불확실한 경우 가변인수를 사용할 수 있다.
가변인수는 매개변수 선언 시 뒤에 ...를 붙이거나, 인수 전달 시 리스트를 spread 연산자(...)로 전개하여 사용할 수 있다.

선언 시 매개변수에서 사용하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 SCSS 구문
@mixin baseStyle($fontWeight, $src...) {
    @font-face {
        font-family: base-font;
        font-weight: $fontWeight;
        src: $src;
    }
}

@include baseStyle(
    700,
    url("./font/a.woff") format("woff"),
    url("./font/b.woff") format("woff"),
    url("./font/c.woff") format("woff")
);

 컴파일된 CSS 구문
@font-face {
    font-family: base-font;
    font-weight: 700;
    src: url("./font/a.woff") format("woff"),
         url("./font/b.woff") format("woff"),
         url("./font/c.woff") format("woff");
}

인수에서 사용하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 SCSS 구문
@mixin baseStyle($color: red, $width, $height) {
    margin: 0;
    padding: 0;
    background-color: $color;
    width: $width;
    height: $height;
}

.box1 {
    $style: (white, 100px, 200px);
    @include baseStyle($style...);
}

 컴파일된 CSS 구문
.box1 {
    margin: 0;
    padding: 0;
    background-color: white;
    width: 100px;
    height: 200px;
}

@extend

@extend를 사용하면 스타일 속성이 병합되어 합쳐지는 것이 아닌 선택자가 추가되는 방식이다.
@extend 대신 @mixin을 사용하는 것을 권장한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 SCSS 구문
.btn {
    color: red;
}
.btn-error {
    @extend .btn;
    background-color: blue;
}

 컴파일된 CSS 구문
.btn, .btn-error {
    color: red;
}
.btn-error {
    background-color: blue;
}

@for

for through와 for to가 있다.
for through : 마지막 순서까지 순회

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 SCSS 구문
@for $변수 from 시작 through 종료 {}

$colorList: ('red', 'blue', 'green');
@for $i from 1 through length($colorList) {
    div:nth-child(#{$i}) {
        color: nth($colorList, $i);
    }
}

 컴파일된 CSS 구문
div:nth-child(1) {
    color: red;
}
div:nth-child(2) {
    color: blue;
}
div:nth-child(3) {
    color: green;
}

for to : 마지막 순서 전까지 순회

1
2
 SCSS 구문
@for $변수 from 시작 to 종료 {}

@each

JS for in과 비슷하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 SCSS 구문
@each $변수 in 데이터 {반복 내용}

$fruits: ('apple', 'banana', 'cherry');
@each $fruit in $fruits {
    li.#{$fruit} {
        background: url('/image/#{$fruit}.png');
    }
}

 컴파일된 CSS 구문
li.apple {
    background: url('/image/apple.png');
}
li.banana {
    background: url('/image/banana.png');
}
li.cherry {
    background: url('/image/cherry.png');
}

인덱스값이 필요할 경우 index() 내장 함수를 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 SCSS 구문
@each $변수 in 데이터 {반복 내용}

$fruits: ('apple', 'banana', 'cherry');
@each $fruit in $fruits {
    $index: index($fruits, $fruit);

    li:nth-child(#{$index}) {
        background: url('/image/#{$index}.png');
    }
}

 컴파일된 CSS 구문
li:nth-child(1) {
    background: url('/image/1.png');

@if

JS의 if문과 비슷하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 SCSS 구문
$color: orange;
div {
    @if $color == strawberry {
        color: pink;
    } @else if $color == orange {
        color: orange;
    } @else {
        color: green;
    }
}


 컴파일된 CSS 구문
div {
    color: orange;
}

논리 연산(and, or, not)을 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 SCSS 구문
@function limitSize($size){
    @if $size > 0 and $size < 200 {
        @return 150px;
    } @else {
        @return 800px;
    }
}

div {
    width: limitSize(300);
}

 컴파일된 CSS 구문
div {
    width: 800px;
}

if

삼항연산자와 비슷하다. 조건이 참이면 표현식1을, 거짓이면 표현식2를 반환한다.

기본 구문

1
2
3
4
5
6
7
8
9
10
11
12
 SCSS 구문
if (조건, 표현식1, 표현식2)

$truthy: true;
div {
    color: if($truthy == true, blue, red);
}

 컴파일된 CSS 구문
div {
    color: blue;
}

@function

계산된 값을 반환하고 싶을 때 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 SCSS 구문
@function sum($a, $b) {
    $result: $a + $b;
    @return #{$result}px;
}

div {
    width: sum(10,20);
    height: sum(30,20);
}

 컴파일된 CSS 구문
div {
    width: 30px;
    height: 50px;
}

& (Ampersand)

부모의 선택자를 참조한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 SCSS 구문
div {
    width: 100px;

    &.active {
        color: red;
    }
}

 컴파일된 CSS 구문
div {
    width: 100px;
}
div.active {
    color: red;
}

응용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 SCSS 구문
.card {
    width: 100px;

    &-error {
        color: red;
    }
    &-notice {
        color: blue;
    }
    
}

 컴파일된 CSS 구문
.card {
    width: 100px;
}
.card-error {
    color: red;
}
.card-notice {
    color: blue;
}

@at-root

부모 바깥에 선택자를 정의하고 싶을 때 사용한다. (중첩에서 벗어나고 싶을 때 사용)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 SCSS 구문
div.header {
    $customFont: bold;

    font-weight: $customFont;

    @at-root div.main {
        font-weight: $customFont;
    }
}

 컴파일된 CSS 구문
div.header {
    font-weight: bold;
}
div.main {
    font-weight: bold;
}

#{} (문자 보간법)

보간: 사이를 채우다.
보간법: 알려진 값을 기반으로 값을 계산하는 프로세스입니다.
변수의 이름을 문자열로 표시하지 않고 값으로 반환한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 SCSS 구문
div.header {
    $baseSize: 100;

    $customWidth: $baseSize%;  /* ❌ 올바르지 않은 구문 */
    $customHeight: #{$baseSize}px;  /* ✅ */

    width: $customWidth;
    height: $customHeight;
}

 컴파일된 CSS 구문
div.header {
    width: $baseSize%; /* ❌ 올바르지 않은 구문 */
    height: 100px; /* ✅ */
}

!default

할당되어 있는 변수가 있다면 기존 할당값을 사용한다.
의도치 않게 변수명 중복 시 스타일 덮어쓰기를 방지하기 위함.

1
2
3
4
5
6
7
8
9
10
11
12
 SCSS 구문
$baseSize: 100px;
div.header {
    $baseSize: 50px !default;

    width: $baseSize;
}

 컴파일된 CSS 구문
div.header {
    width: 100px; 
}

@content

vue의 slot 같은 기능
@mixin 내에 @content를 사용하면 @include시에 해당부분에 스타일 블록을 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 SCSS 구문
@mixin cardStyle(){
    font-size: 16px;
    font-weight: 400;
    @content;
}

div-error {
    @include cardStyle(){
        color: red;
    }
}

 컴파일된 CSS 구문
div-error {
    font-size: 16px;
    font-weight: 400;
    color: red;
}

@import

⚠ deprecated
외부에서 가져온 Sass 파일은 모두 단일 CSS 파일로 병합된다.
현재는 @use를 사용하는 것을 권장한다.

@use

SCSS 간에 파일을 사용할 때 사용한다.
@import와 달리 네임스페이스를 지원하며, 모듈 시스템을 제공한다.

파일 분할

파일명이 언더바(_)로 시작하는 파일은 부분 파일(partial)이라고 한다.
부분 파일을 @use하면 use한 곳의 CSS로 병합되며, 언더바 파일은 별도로 컴파일되지 않는다.



참조

This post is licensed under CC BY 4.0 by the author.

정보처리기사 필기 합격 방법 및 후기

SEO를 위해 SSR를 써야하는 이유