Frontend/Sass(SCSS)

SCSS 문법(3) - 반복문, 함수, 가져오기

고코모옹 2021. 5. 29. 14:46
  • 반복문
    • 스타일을 반복적으로 출력
// through: 종료만큼 반복
@for $i from 1 through 3 {
    .box:nth-child(#{$i}) {
        width: 100px;
    }
}
// to: 종료 직전까지 반복
@for $i from 1 to 3 {
    .box:nth-child(#{$i}) {
        width: 100px;
    }
}
// SCSS
@for $i from 1 through 3 {
    .box:nth-child(#{$i}) {
        width: 100px * $i;
    }
}

@for $i from 1 to 3 {
    .box:nth-child(#{$i}) {
        width: 100px * $i;
    }
}

// CSS (Compiled to)
.box:nth-child(1) {
  width: 100px;
}

.box:nth-child(2) {
  width: 200px;
}

.box:nth-child(3) {
  width: 300px;
}

.box:nth-child(1) {
  width: 100px;
}

.box:nth-child(2) {
  width: 200px;
}

  • 함수
    • Mixin과 유사하지만 반환되는 내용이 다름
    • Mixin은 스타일을 반환하지만, 함수는 보통 연산된 특정 값을 @return 지시어를 통해 반환
// SCSS
@mixin center {
    display: flex;
    justify-content: center;
    align-items: center;
}

@function ratio($size, $ratio) {
    @return $size  * $ratio;
}

.box {
    $width: 100px;
    width: $width;
    height: ratio($width, 1/2);
    @include center;
}

// CSS (Compiled to)
.box {
  width: 100px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

  • 색상 내장 함수
    • mix($color1, $color2) : 두 개의 색을 섞는다.
    • lighten($color, $amount) : 더 밝은색을 만든다.
    • darken($color, $amount) : 더 어두운색을 만든다. 
    • saturate($color, $amount) : 색상의 채도를 올린다.
    • desaturate($color, $amount) : 색상의 채도를 낮춘다.
    • grayscale($color) : 색상을 회색으로 변환한다.
    • invert($color) : 색상을 반전시킨다.
    • rgba($color, $alpha) : 색상의 투명도를 변경한다.

  • 가져오기
    • @import "./sub", "./sub2";
    • url 함수 및 확장자 생략 가능.
    • 여러개의 파일을 가져올 경우 쉼표(,)로 가능