SASS 的條件判斷
本文說明 SASS 中的條件判斷。
我們以實用範例,清楚講解從基礎到進階的條件判斷用法,涵蓋 @if、@else if、@else 指令。
YouTube Video
SASS 的條件判斷
SASS 是一種擴充 CSS 的樣式表語言,透過條件判斷可以更彈性地控制樣式。在 SASS 中,可以使用 @if、@else if、@else 於編譯時切換樣式輸出。
基本條件語法
SASS 的基本條件判斷可用以下語法撰寫。
1@if condition {
2 // Code executed when the condition is true
3} @else if condition {
4 // Code executed when another condition is true
5} @else {
6 // Code executed when all conditions are false
7}@if會先判斷第一個條件,若為假,則依序評估@else if或@else區塊。
簡單條件範例
在以下範例中,背景色會依據 $theme 變數切換。
1$theme: "dark";
2
3body {
4 @if $theme == "dark" {
5 background-color: #333;
6 color: #fff;
7 } @else if $theme == "light" {
8 background-color: #fff;
9 color: #000;
10 } @else {
11 background-color: #f0f0f0;
12 color: #333;
13 }
14}編譯後的 CSS
1body {
2 background-color: #333;
3 color: #fff;
4}- 當
$theme為"dark"時,會套用深色背景與白色文字。
將條件與計算結合
條件判斷不僅能處理字串與顏色的比較,也能進行數值計算。
1$width: 1200px;
2
3.container {
4 @if $width > 1000px {
5 max-width: 1200px;
6 } @else {
7 max-width: 800px;
8 }
9}編譯後的 CSS
1.container {
2 max-width: 1200px;
3}- 也可以進行數值比較;當
$width超過 1000px 時,會輸出max-width: 1200px。
巢狀條件判斷
透過巢狀條件可以表達更複雜的情況。
1$theme: "dark";
2$size: "large";
3
4button {
5 @if $theme == "dark" {
6 background-color: #000;
7 color: #fff;
8
9 @if $size == "large" {
10 padding: 20px;
11 } @else {
12 padding: 10px;
13 }
14 } @else {
15 background-color: #fff;
16 color: #000;
17
18 @if $size == "large" {
19 padding: 15px;
20 } @else {
21 padding: 8px;
22 }
23 }
24}編譯後的 CSS
1button {
2 background-color: #000;
3 color: #fff;
4 padding: 20px;
5}- 巢狀條件讓你能同時依主題與尺寸來套用樣式。
在自訂函式中使用條件判斷
在自訂函式內使用條件判斷可提升重用性。
1@function adjust-color($theme) {
2 @if $theme == "dark" {
3 @return #333;
4 } @else if $theme == "light" {
5 @return #fff;
6 } @else {
7 @return #ccc;
8 }
9}
10
11.card {
12 background-color: adjust-color("dark");
13}編譯後的 CSS
1.card {
2 background-color: #333;
3}- 將條件封裝於函式中,可提升重用性與可維護性。
實用範例 - 切換設計
來看一個依條件切換整體設計的範例。
1$theme: "light";
2
3body {
4 font-family: Arial, sans-serif;
5
6 @if $theme == "dark" {
7 background-color: #121212;
8 color: #e0e0e0;
9 } @else if $theme == "light" {
10 background-color: #f9f9f9;
11 color: #333;
12 } @else {
13 background-color: #fff;
14 color: #000;
15 }
16}
17
18header {
19 @if $theme == "dark" {
20 border-bottom: 1px solid #333;
21 } @else {
22 border-bottom: 1px solid #ccc;
23 }
24}編譯後的 CSS
1body {
2 font-family: Arial, sans-serif;
3 background-color: #f9f9f9;
4 color: #333;
5}
6
7header {
8 border-bottom: 1px solid #ccc;
9}- 可依據主題變數動態切換整個頁面的配色方案。
注意事項與最佳實務
在使用 SASS 條件式時,可以考慮以下幾點。
-
保持條件判斷簡潔
過度巢狀會降低可讀性,因此善用函式與 mixin 可保持簡潔。
-
以變數與函式進行抽象化
若在多處使用相似條件,將其整合為變數或函式能提升可維護性。
-
避免邏輯臃腫
盡可能統一設計規則,避免過度使用條件判斷。
結論
SASS 的條件判斷是打造彈性且動態樣式的有效工具。本文由淺入深,逐步說明從基礎到實務範例的內容。在實際專案中使用條件判斷時,請以可重用的程式碼為目標,並避免讓邏輯過於複雜。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。