Frontend/Sass(SCSS)

SCSS 문법(2) - 변수, 연산, 재활용(Mixin)

고코모옹 2021. 5. 29. 03:43
  • 변수(Variables)
    • 반복적으로 사용되는 값을 변수로 지정
    • 변수이름 앞에 $추가 ( $변수이름: 속성값; )
    • 유효범위는 {} 기준
    • 변수가 재할당되면 그 이후에 사용되는 변수는 재할당 된 값으로 사용
      (left 속성은 200px이 아닌 300px이 할당됨)
// SCSS
$globalSize: 100px;    //전역변수

.container {
    $localSize: 200px;    //지역변수
    positon: fixed;
    top: $localSize;
    .item {
        $localSize: 300px;    //재할당
        width: $globalSize;
        height: $globalSize;
        transform: translateX($localSize);
    }  
    left: $localSize;
}

// CSS (Compiled to)
.container {
  positon: fixed;
  top: 200px;  
  left: 300px;
}
.container .item {
  width: 100px;
  height: 100px;
  transform: translateX(300px);
}

  • 연산(Operations)
    • 나누기 연산자는 주의 필요(CSS 단축 속성으로 해석되므로 아래와 같이 사용)
      1. 괄호
      2. 변수할당 후 사용
      3. 다른 연산자와 함께 사용
    • 주의사항
      • 곱하기(*) : 하나 이상의 값이 반드시 숫자
      • 나누기(/) : 오른쪽 값이 반드시 숫자
// SCSS
div {
    $size: 30px;
    width: 20px + 20px;
    height: 40px - 10px;
    font-size: 10px * 2;
    margin: (30px / 2);        // 1.
    margin: $size / 2;        // 2.
    margin: (10px + 12px) / 2;    // 3.
    padding: 20px % 7;
}

// CSS (Compiled to)
div {
  width: 40px;
  height: 30px;
  font-size: 20px;
  margin: 15px;
  margin: 15px;
  margin: 11px;
  padding: 6px;
}

  • 재활용(Mixins)
    • 재사용 할 CSS 선언 그룹을 정의하는 기능
    • @mixin으로 선언하고 @include로 사용
    • 속성은 같으나 값이 다를 경우에는 인수를 사용
// SCSS
@mixin center {
    display: flex;
    justify-content: center;
    align-items: center;
}
.container {
    @include center;
    .item {
        @include center;
    }
}
.box {
    @include center;
}

// CSS (Compiled to)
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.container .item {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

// SCSS
@mixin box($size: 100px, $color: tomato) {    // 기본값 설정
    width: $size;
    height: $size;
    background-color: $color;
}
.container {
    @include box(200px, red);
    .item {
        @include box($color: green);    // 색상만 변경(키워드 인수)
    }
}
.box {
    @include box();
}

// CSS (Compiled to)
.container {
  width: 200px;
  height: 200px;
  background-color: red;
}
.container .item {
  width: 100px;
  height: 100px;
  background-color: green;
}

.box {
  width: 100px;
  height: 100px;
  background-color: tomato;
}