프로그래밍/Sass

[Sass/SCSS] 문법 - 변수(Variables)

미냐님 2020. 3. 26. 23:27
728x90

Sass(SCSS) 문법 - 변수(Variables)

  • 반복적으로 사용되는 값을 변수로 지정할 수 있습니다.
  • 변수 이름 앞에는 항상 $를 붙입니다
  • $변수이름: 속성값;
  • SCSS:
$color-primary: #e96900;
$url-images: "/images/";
$w: 200px;

.box {
  width: $w;
  margin-left: $w;
  background: $color-primary url($url-images + "bg.jpg");
}
  • Compiled to:
.box {
  width: 200px;
  margin-left: 200px;
  background: #e96900 url("/images/bg.jpg");
}

변수 유효범위(Variable Scope)

  • 변수는 사용 가능한 유효범위가 있습니다.
  • 선언된 블록({}) 내에서만 유효범위를 가집니다.
  • 변수 $color는 .box1의 블록 안에서 설정되었기 때문에, 블록 밖의 .box2에서는 사용할 수 없습니다
.box1 {
  $color: #111;
  background: $color;
}

// Error
.box2 {
  background: $color;
}

변수 재 할당(Variable Reassignment)

  • 다음과 같이 변수에 변수를 할당할 수 있습니다.

  • SCSS:

$red: #FF0000;
$blue: #0000FF;

$color-primary: $blue;
$color-danger: $red;

.box {
  color: $color-primary;
  background: $color-danger;
}
  • Compiled to:
.box {
  color: #0000FF;
  background: #FF0000;
}

!global (전역 설정)

  • !global 플래그를 사용하면 변수의 유효범위를 전역(Global)로 설정할 수 있습니다.

  • SCSS:

.box1 {
  $color: #111 !global;
  background: $color;
}
.box2 {
  background: $color;
}
  • Compiled to:
.box1 {
  background: #111;
}
.box2 {
  background: #111;
}
  • 기존에 사용하던 같은 이름의 변수가 있을 경우 값이 덮어져 사용될 수 있습니다.

  • SCSS:

$color: #000;
.box1 {
  $color: #111 !global;
  background: $color;
}
.box2 {
  background: $color;
}
.box3 {
  $color: #222;
  background: $color;
}
  • Compiled to:
.box1 {
  background: #111;
}
.box2 {
  background: #111;
}
.box3 {
  background: #222;
}

!default (초깃값 설정)

  • !default 플래그는 할당되지 않은 변수의 초깃값을 설정합니다.

  • 즉, 할당되어있는 변수가 있다면 변수가 기존 할당 값을 사용합니다.

  • SCSS:

$color-primary: red;

.box {
  $color-primary: blue !default;
  background: $color-primary;
}
  • Compiled to:
.box {
  background: red;
}
  • 좀 더 유용하게, ‘변수와 값을 설정하겠지만, 혹시 기존 변수가 있을 경우는 현재 설정하는 변수의 값은 사용하지 않겠다’는 의미로 쓸 수 있습니다.
    예를 들어, Bootstrap 같은 외부 Sass(SCSS) 라이브러리를 연결했더니 변수 이름이 같아 내가 작성한 코드의 변수들이 Overwrite(덮어쓰기) 된다면 문제가 있겠죠.
    반대로 내가 만든 Sass(SCSS) 라이브러리가 다른 사용자 코드의 변수들을 Overwrite 한다면, 사용자들은 그 라이브러리를 더 이상 사용하지 않을 것입니다.
    이럴 때 Sass(SCSS) 라이브러리(혹은 새롭게 만든 모듈)에서 사용하는 변수에 !default 플래그가 있다면 기존 코드(원본)를 Overwrite 하지 않고도 사용할 수 있습니다.

  • SCSS:

// _config.scss
$color-active: red;

// main.scss
@import 'config';

$color-active: blue !default;

.box {
  background: $color-active;  // red
}
728x90

'프로그래밍 > Sass' 카테고리의 다른 글

[Sass/SCSS] 재활용(Mixins) - @include  (0) 2020.03.26
[Sass/SCSS] 가져오기(Import)  (0) 2020.03.26
[Sass/SCSS] 문법 - 중첩  (0) 2020.03.26
[Sass/SCSS] 문법 - 주석  (0) 2020.03.26
Sass(SCSS) 컴파일 방법  (0) 2020.03.26