Ga Tech

1.01 everyday

Scss - variable

Scss - variable。

variable type

Boolean

$rounded: false;
$shadow: true;

Numbers (可寫單位)

$rounded: 4px;
$line-height: 1.5;
$font-size: 3rem;

Colors

$base: purple;
$border: rgba(0, 255, 0, 0.5);
$shadow: #333;

Strings

$header: 'My Head';
$callout: Arial;
$message: "Oops...";

Lists

$authors: Mike, John, Tom;
$margin: 40px 0 20px 100px;

Null

$shadow: null;

variable scope

在 selector 裡頭改變 variable,global variable 也會隨之改變:

application.scss
1
2
3
4
5
6
7
8
9
$color-base: #777777;
.sidebar {
$color-base: #222222;
background: $color-base;
}
p {
color: $color-base;
}

產生:

application.css
1
2
3
4
5
6
.sidebar {
background: #222222;
}
p {
color: #222222;
}

#{$variable}

可以用 #{variable} 的方式來將變數套到 selectors, property names, 或是 strings:

application.scss
1
2
3
4
5
6
7
8
9
$side: top;
sup {
position: relative;
#{$side}: -0.5em; // 變成 top: -0.5em;
}
.callout-#{$side} { // 變成 .callout-top
background: #777;
}

!default

預設情況下,後來設定的變數會覆蓋掉先前的變數:

application.scss
1
2
3
4
5
6
$title: 'First Title';
$title: 'Second Title';
h2:before {
content: $title;
}

產生:

application.css
1
2
3
h2:before {
content: 'Second Title';
}

但如果在設定變數後面新增 !default,就可以避免覆蓋掉先前的變數:

application.scss
1
2
3
4
5
6
$title: 'First Title';
$title: 'Second Title' !default;
h2:before {
content: $title;
}
application.css
1
2
3
h2:before {
content: 'First Title';
}

Comments