본문 바로가기

달밤에 코딩하기/Sass & SCSS

#8 - SCSS 변수 - 사용법 / 적용 범위 / 재할당

 

변수 사용

반복 사용되는 값을 지정하여 사용할 수 있다.

SCSS

/* $속성이름 : 속성값; */
$color-primary: #000000;
$url: "./image/";

.bg{
  background: $color-primary url($url + "bg.png");
}

Compile 된 CSS

.bg{
  background : #000000 url("./image/bg.png");
}

 


 

변수 적용 범위

변수($)는 선언된 영역( { } 대괄호 영역)에서만 동작한다.

SCSS

/* 전역에 사용하는 변수 */
$color: red;

/* class1에서만 사용하는 변수 */
.class1 {
  $per100: 100%;
  $per50: 50%;
  
  width: $per100;
  height: $per50;
  background-color: $color;
  
  @at-root .class2 {
    width: $per100;
    height: $per50;
    background-color: $color;
  }
}

/* class3 요소는 변수 선언 밖에 있기 때문에 동작하지 않는다.*/
.class3 {
    width: $per100;
    height: $per50;
    background-color: $color;
}

Compile 된 CSS

.class1 {
  width: 100%;
  height: 50%;
}
.class2 {
  width: 100%;
  height: 50%;
}
.class3 {
  background-color: red;
}

 


변수 재할당

변수에 변수 할당이 가능하다.

SCSS

$black : #000000;
$gray: #666666;

$color-primary: $black;
$color-gray: $gray;

.bg{
  background: $color-primary;
  color: $gray;
}

Compile 된 CSS

.bg{
  background: #000000;
  color: #666666;
}