$를 넣어서 사용한다.문자열, 숫자, 색상, 불리언(true, false), 리스트(Array), null이다.
변수 문법 코드$url-sprite: '../img/'; $color-red: #ff0000;
자바스크립트와 유사하게 SassScript 변수도 범위를 가지며, 전역 변수와 지역 변수 두 개로 나뉘어진다.
해당 변수를 할당, !default(변수값 초기화 설정), ${}(문자 보간)을 이용하여 코드 어디에서든 변수를 쓸 수 있다.
전역 변수라고 부른다.//전역변수
$url-sprite: '../img/';
$color-red: #ff0000;
$width: 50%;
div{
color:$color-red;
background:url($url-sprite + 'sp_icon.png') no-repeat 0 0;
}
p{
width:$width;
}
/* CSS 컴파일 결과 */
div{
color:#ff0000;
background:url('../img/sp_icon.png') no-repeat 0 0;
}
p{
width:50%;
}
class 또는 id가 선언된 블록코드 {} 내에서만 유효범위를 가진다.지역변수는 규칙의 중첩 수준에 따라 사용할 수 있는 지역의 범위가 한정된다.지역변수는 정의한 블록의 상위 부모 블록에서 사용할 수 없다.!global 플래그를 사용하면 전역변수로 사용할 수 있다.div{
$url-sprite: '../img/'; //지역변수
$color-red: #ff0000; //지역변수
$width: 50% !glogal; //!global 전역변수
color:$color-red;
background: url($url-sprite + 'sp_icon.png') no-repeat 0 0;
}
p{
width:$width;
}
$width: 100%;
$box-width: $width; //변수에 변수를 할당
.box-width{
width:$box-width;
}
!default 플래그를 사용하여 할당되지 않은 변수의 초기값을 설정할 수 있다.
!default플래그가 사용되었을 경우, 만약 이전에 할당값이 없다면!default와 함께 작성된 값이 할당된다.
만약, 이전에 할당된 값이 있다면!default플래그는 무시된다.
$content: "Hello World!";
$content: "환영합니다";
$content: "안녕하세요" !default; // 재할당 무시
/* CSS 컴파일 결과 */
#main {
content: $content; // "환영합니다"
}
#{}를 이용하여 어디서든 변수값을 문자열로 넣을 수 있다.$line-left: left;
$value25: 25;
$value77: 77;
.box-string_v1{
border - #{$line-left}: 1px solid #333; //문자 보간
}
//숫자 값인 변수를 + 연결하면 연산되어 102값이 나온다
.box-variables{
width: $value25 + $value77 + px;
}
//문자 보간으로 변수를 + 연결하면 문자값인 2577이 나온다.
.box-string_v2{
width: #{value25} + #{value77} + px;
}
/* CSS 컴파일 결과 */
.box-string_v1{
border-left:1px solid #333;
}
.box-variables{
width:102px;
}
.box-string_v2{
width:2577px;
}