跳至主要内容

25 篇文章 含有標籤「CSS」

檢視所有標籤

Web 前端效能優化入門教學筆記 | 學習筆記

· 閱讀時間約 4 分鐘
kdchang

在網頁開發中,效能優化是一個不可忽視的重要課題。無論是企業網站、單頁應用(SPA),或是電商平台,效能表現都直接影響使用者體驗與轉換率。

本篇筆記將介紹 Web 前端效能優化的核心概念、常見策略與實務範例,幫助你為專案建立良好的基礎。


為什麼需要前端效能優化?

前端效能不佳會導致:

  • 首次載入時間過長
  • 使用者等待過久,產生跳出行為
  • SEO 表現不佳(Google 會參考 LCP、CLS、FCP 等指標)

透過有效的優化策略,我們能讓網站更快、更穩、更吸引人。


效能優化的三個層面

  1. 載入效能(Loading Performance):提升頁面初始載入速度。
  2. 互動效能(Interaction Performance):優化點擊、滑動等互動的流暢度。
  3. 渲染效能(Rendering Performance):減少重繪、重排與動畫卡頓。

一、減少不必要的資源請求

使用 CDN

透過 CDN(Content Delivery Network)可將靜態資源分發到全球節點,加速載入。

<!-- 使用 Google Fonts CDN -->
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet" />

合併與壓縮資源(Minify & Bundle)

使用打包工具如 Webpack、Vite,可以:

  • 將 JS / CSS 壓縮(Minify)
  • 移除註解與空白
  • 合併多個檔案減少 HTTP 請求數量

範例(Webpack 設定簡略):

// webpack.config.js
module.exports = {
mode: 'production', // 自動啟用壓縮
entry: './src/index.js',
output: {
filename: 'bundle.js',
},
};

二、圖片與多媒體優化

適當圖片格式

  • 使用 WebPAVIF 取代 JPEG / PNG,可減少檔案體積 25% 以上
  • SVG 適用於圖示與 icon,解析度不會失真

延遲載入圖片(Lazy Loading)

<img src="thumbnail.jpg" loading="lazy" alt="延遲載入圖片" />

或搭配 JavaScript 實現滾動載入。


三、有效使用 Cache(快取)

設定 Cache-Control 標頭

在伺服器上設定靜態資源快取策略:

Cache-Control: max-age=31536000, immutable

適用於版本化的資源檔案(如 main.123abc.js),可快取一年不變。


四、精簡 CSS 與 JavaScript

移除未使用的 CSS(Tree Shaking)

使用工具如 PurgeCSSTailwindCSS JIT Mode 可自動剔除沒用到的樣式。

PurgeCSS 使用方式(簡略):

const purgecss = require('@fullhuman/postcss-purgecss');

module.exports = {
plugins: [
purgecss({
content: ['./**/*.html'],
}),
],
};

延遲載入 JS(Defer / Async)

<script src="main.js" defer></script>
  • defer: 等 DOM 解析完才執行,不阻塞渲染
  • async: 載入完成即執行,適合非必要腳本(如 GA)

五、避免過度重排與重繪

使用 class 切換取代 style 修改

重複直接操作 DOM style 屬性會導致效能下降,改用 CSS class 控制樣式較佳。

// 不推薦
element.style.width = '100px';
element.style.height = '50px';

// 推薦
element.classList.add('resized');
.resized {
width: 100px;
height: 50px;
}

使用 transformopacity 進行動畫

避免透過 topleftwidth 等影響 layout 的屬性來做動畫。

/* 推薦做法:使用 transform */
.card {
transition: transform 0.3s ease;
}
.card:hover {
transform: scale(1.05);
}

六、最佳化 DOM 結構與渲染

  • 減少過深的 DOM 巢狀結構
  • 使用虛擬滾動(Virtual Scroll)載入大量列表
  • 避免頻繁操作 DOM,應該一次性改動(使用 DocumentFragment 或 requestAnimationFrame)

七、使用開發工具檢查效能

Chrome DevTools

  1. Lighthouse:提供整體效能建議
  2. Performance Panel:檢查 JS 執行、動畫、Layout shift 等問題
  3. Network Panel:觀察資源大小、載入順序與快取狀態

總結與建議實作順序

若你剛開始進行專案的效能優化,可以依照以下順序著手:

  1. 壓縮與合併 JS / CSS
  2. 圖片格式轉換與 Lazy Load
  3. CDN 部署靜態資源
  4. 移除未使用樣式與延遲載入腳本
  5. 改善動畫與 DOM 操作
  6. 導入快取策略
  7. 使用 Lighthouse 檢查並優化問題

效能優化並非一次性工作,而是一個持續調整的過程。建議我們可以從專案開始就納入效能考量,將它當成基本開發原則來實踐。

參考文件

  1. Core Web Vitals: An everyday explanation (Taiwanese with English subtitles)

PostCSS 入門教學筆記 | 學習筆記

· 閱讀時間約 4 分鐘
kdchang

一、什麼是 PostCSS?

PostCSS 是一個 CSS 的轉換工具(CSS Transformer),本身不是 CSS 預處理器(如 Sass)或框架(如 Tailwind CSS),但它可以透過「外掛(plugin)」的方式強化你的 CSS 工作流程。

簡單來說,PostCSS 是一個平台,讓你可以用 JavaScript 編寫規則,自動處理 CSS,像是:

  • 自動加上瀏覽器前綴(autoprefixer)
  • 支援未來 CSS 語法(例如 Nesting)
  • 壓縮 CSS、移除重複樣式
  • 搭配 Tailwind CSS 進行原子化設計

二、PostCSS 的運作原理

PostCSS 的流程如下:

  1. 將原始 CSS 解析為 AST(抽象語法樹)
  2. 透過插件對 AST 進行操作
  3. 將修改後的 AST 轉回 CSS 輸出

你可以選擇使用官方插件、社群插件,甚至自己寫 plugin。


三、如何安裝與設定 PostCSS

安裝(使用 npm)

npm install -D postcss postcss-cli autoprefixer

建立 PostCSS 設定檔 postcss.config.js

module.exports = {
plugins: [
require('autoprefixer'),
],
};

這樣 PostCSS 就會讀取這個設定檔,並在處理 CSS 時自動加入瀏覽器前綴。


四、基本使用流程

假設你有一個檔案 src/style.css

/* src/style.css */
:root {
--main-color: #4f46e5;
}

.btn {
display: flex;
background-color: var(--main-color);
user-select: none;
}

執行 PostCSS 處理:

npx postcss src/style.css -o dist/style.css

這會根據你的 postcss.config.js 處理並輸出到 dist/style.css

輸出結果可能為:

:root {
--main-color: #4f46e5;
}

.btn {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
background-color: var(--main-color);
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

這就是 autoprefixer 自動補完各種瀏覽器相容性的結果。


五、常用插件介紹與範例

1. autoprefixer(最常見)

自動加上 CSS 瀏覽器前綴

npm install -D autoprefixer

可搭配 .browserslistrcpackage.json 設定支援目標:

> 1%
last 2 versions
not dead

2. postcss-preset-env

支援未來 CSS 語法,例如 Nesting、變數、邏輯函數等

npm install -D postcss-preset-env

更新設定檔:

module.exports = {
plugins: [
require('postcss-preset-env')({
stage: 1,
}),
],
};

然後你就可以寫類似這樣的 CSS:

.btn {
color: white;

&:hover {
color: black;
}
}

經過 PostCSS 處理後會被轉成瀏覽器可讀的標準語法。


3. cssnano(壓縮 CSS)

這個插件會讓 CSS 變得更小,適合生產環境使用:

npm install -D cssnano
module.exports = {
plugins: [
require('autoprefixer'),
require('cssnano')({
preset: 'default',
}),
],
};

六、PostCSS 與 Tailwind CSS 的關係

Tailwind CSS 是建立在 PostCSS 基礎上的一個插件。因此在安裝 Tailwind 時你會看到:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

這個指令會產生 postcss.config.js

module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

Tailwind 本身就是一個 PostCSS 插件,會將你在 HTML 或 JSX 中寫的 class 轉換成實際的 CSS。


七、PostCSS 與其他工具整合

搭配 Vite

Vite 專案中只要有 postcss.config.js 檔案,會自動載入設定,不需額外安裝。

搭配 Webpack

webpack.config.js 加入:

module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
],
}

八、自訂 PostCSS 插件(進階)

你也可以自己撰寫插件來操作 CSS AST:

module.exports = () => {
return {
postcssPlugin: 'my-plugin',
Declaration(decl) {
if (decl.prop === 'color' && decl.value === 'red') {
decl.value = 'blue';
}
},
};
};
module.exports.postcss = true;

這個簡單的插件會把 color: red 自動換成 color: blue


九、總結

PostCSS 雖然不像 Sass 有自己的語法,也不像 Tailwind 有明確的設計架構,但它是現代前端 CSS 處理流程中不可或缺的工具,擁有高度彈性與強大生態系。

我們可以根據需求只加幾個插件,也可以像 Tailwind 那樣完全建構在它上面。尤其當你的專案需要支援多瀏覽器、使用最新 CSS 語法、進行建置壓縮時,PostCSS 是最佳解法之一。

如果你正在使用 Vite、Next.js、或是 Tailwind CSS,幾乎都已內建 PostCSS 支援。了解它的運作方式能幫你更精準地控制前端樣式處理流程。

AOS(Animate On Scroll Library)入門教學筆記 | 學習筆記

· 閱讀時間約 5 分鐘
kdchang

在現代網頁設計中,視覺效果和互動性已經成為提升使用者體驗的重要元素。當使用者向下滾動頁面時,如果某些區塊能夠平滑地出現、滑入、淡入或放大,能大大提升網站的專業感和吸引力。這類效果通常被稱為「滾動動畫」。

AOS (Animate On Scroll) 是一個輕量級的 JavaScript 函式庫,讓你可以輕鬆地為 HTML 元素加上動畫效果,並且在元素進入畫面時自動播放動畫。它不需要你手動寫 JavaScript 控制事件,也不依賴大型框架,學習曲線平緩,非常適合想快速加上動畫效果的開發者。


一、AOS 的特點

  • 輕量:只有數十 KB,對效能影響小。
  • 易於使用:只需要加幾個 data-aos 屬性在 HTML 元素上即可。
  • 可自訂動畫:支援動畫類型、延遲時間、持續時間、執行次數等調整。
  • 無框架依賴:可搭配純 HTML/CSS/JS 使用,也支援 React、Vue 等框架。
  • 良好的瀏覽器支援:支援所有現代瀏覽器。

二、如何安裝 AOS

方法一:使用 CDN(最簡單方式)

在你的 HTML 檔案 <head> 加入 CSS:

<link href="https://unpkg.com/aos@2.3.4/dist/aos.css" rel="stylesheet">

<body> 結尾加入 JS:

<script src="https://unpkg.com/aos@2.3.4/dist/aos.js"></script>
<script>
AOS.init();
</script>

方法二:透過 npm 安裝(建議在模組化專案中使用)

npm install aos --save

在你的 JavaScript 中引入與初始化:

import AOS from 'aos';
import 'aos/dist/aos.css';

AOS.init();

三、基本用法

只要在 HTML 元素上加入 data-aos 屬性即可。例如:

<div data-aos="fade-up">
這段文字將會在滾動時從下方淡入出現
</div>

常見的動畫效果:

效果名稱說明
fade淡入
fade-up向上淡入
fade-down向下淡入
fade-left向左淡入
fade-right向右淡入
zoom-in放大淡入
zoom-out縮小淡入
flip-left向左翻轉進場
slide-up向上滑入
slide-down向下滑入

四、進階設定

AOS 提供許多自訂參數,以下為常用屬性說明:

1. data-aos-duration

動畫持續時間(毫秒),預設為 400ms:

<div data-aos="fade-up" data-aos-duration="1000">
動畫持續 1 秒
</div>

2. data-aos-delay

動畫延遲時間(毫秒),可用來讓多個元素依序出現:

<div data-aos="fade-up" data-aos-delay="0">第一個</div>
<div data-aos="fade-up" data-aos-delay="200">第二個</div>
<div data-aos="fade-up" data-aos-delay="400">第三個</div>

3. data-aos-once

設定是否只執行一次動畫(預設為 false,表示每次滾動進入都會重新動畫):

<div data-aos="fade-up" data-aos-once="true">
只播放一次動畫
</div>

4. data-aos-offset

控制動畫啟動前的滾動距離(單位:像素):

<div data-aos="fade-up" data-aos-offset="300">
滾動到距離螢幕頂端 300px 時才開始動畫
</div>

五、實際範例

以下是一個完整的簡單 HTML 範例:

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>AOS 教學範例</title>
<link href="https://unpkg.com/aos@2.3.4/dist/aos.css" rel="stylesheet">
<style>
body {
font-family: sans-serif;
padding: 0;
margin: 0;
}
section {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
border-bottom: 1px solid #ccc;
}
</style>
</head>
<body>

<section>
<div data-aos="fade-up">第一個區塊</div>
</section>

<section>
<div data-aos="zoom-in" data-aos-delay="200">第二個區塊</div>
</section>

<section>
<div data-aos="slide-left" data-aos-duration="800">第三個區塊</div>
</section>

<script src="https://unpkg.com/aos@2.3.4/dist/aos.js"></script>
<script>
AOS.init();
</script>

</body>
</html>

你可以將這段程式碼儲存為 HTML 檔案後,直接打開瀏覽器觀看滾動動畫效果。


六、常見問題與注意事項

  1. AOS 沒有效果?
    確認你有正確載入 aos.css 和執行 AOS.init()

  2. 元素進入畫面但沒有動畫?
    嘗試調整 data-aos-offset 或確認元素是否真的進入視窗中。

  3. 動畫無法重複?
    預設會重複,除非你加上了 data-aos-once="true"

  4. 與 SPA 框架(如 React、Vue)整合時動畫失效?
    動態渲染的頁面需在 DOM 更新完後重新執行 AOS.refresh()


總結

AOS 是一個非常實用又容易上手的前端動畫工具。你不需要寫複雜的 JavaScript,只要加幾行 data-aos 屬性就能為你的網站加入吸引人的動態效果。無論是製作個人作品集、商業網站或展示頁面,AOS 都是快速提升視覺層次感的絕佳利器。

當你需要更細緻的動畫控制或複雜的交互邏輯,也可以進一步探索 GSAPScrollMagic 等更強大的動畫工具。但若只是想快速達到流暢的滾動動畫,AOS 絕對是一個值得推薦的選擇。

參考文件

  1. gsap
  2. scrollmagic

CSS Flexbox align-items 和 align-content 入門教學筆記 | 學習筆記

· 閱讀時間約 3 分鐘
kdchang

在 CSS Flexbox 和 Grid 佈局中,align-itemsalign-content 兩者都與「對齊」有關,但適用的情境不同(單行 vs 多行):

1. align-items

  • 作用於單行內容(單行 Flexbox 或 Grid 容器內的項目)。
  • 控制子元素在**交叉軸(cross-axis)**上的對齊方式。

常見值

說明
stretch預設值,子元素會拉伸填滿容器的交叉軸
flex-start對齊交叉軸的起始點
flex-end對齊交叉軸的結束點
center置中對齊
baseline以文字基線(baseline)對齊

範例

.container {
display: flex;
align-items: center; /* 子元素在交叉軸上置中對齊 */
height: 200px;
border: 1px solid black;
}

.item {
width: 50px;
height: 50px;
background-color: lightblue;
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
</div>

效果item 會在 container 的交叉軸(垂直方向)置中對齊。


2. align-content

  • 作用於多行內容(當 flex-wrap: wrap 或 Grid 有多行時)。
  • 控制整體行的對齊,而不是單個項目。

常見值

說明
stretch預設值,行會拉伸填滿容器
flex-start行對齊交叉軸的起始點
flex-end行對齊交叉軸的結束點
center行置中對齊
space-between第一行靠起始點,最後一行靠結束點,其他行平均分布
space-around每行之間有相等的間距
space-evenly每行之間及兩側間距相等

範例

.container {
display: flex;
flex-wrap: wrap;
align-content: center; /* 整體行群組在交叉軸上置中 */
height: 400px;
border: 1px solid black;
}

.item {
width: 100px;
height: 100px;
background-color: lightcoral;
margin: 5px;
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>

效果:當 .container 高度足夠時,多行 .item 會整體置中排列。


總結

屬性影響對象適用於主要功能
align-items子元素單行(未換行)控制子元素在交叉軸上的對齊
align-content整體行多行(flex-wrap: wrap控制多行的整體對齊

如果容器內只有一行align-content 通常不會有影響,這時候應該使用 align-items

需要 align-content 發揮作用時,請確保:

  1. 容器有 flex-wrap: wrap;(多行)
  2. 容器有足夠的高度(不然內容會自動填滿)

Flexbox Froggy 入門教學筆記 | 學習筆記

· 閱讀時間約 8 分鐘
kdchang

Flexbox(Flexible Box Layout)是一種 CSS3 佈局模式,專門用來設計一維的彈性佈局,適用於水平或垂直排列元素,使網頁排版更加靈活且易於維護。

Flexbox Froggy 透過小青蛙過河遊戲化方式去介紹 Flexbox 使用方式:

Level 1

Welcome to Flexbox Froggy, a game where you help Froggy and friends by writing CSS code! Guide this frog to the lilypad on the right by using the justify-content property, which aligns items horizontally and accepts the following values:

flex-start: Items align to the left side of the container. flex-end: Items align to the right side of the container. center: Items align at the center of the container. space-between: Items display with equal spacing between them. space-around: Items display with equal spacing around them. For example, justify-content: flex-end; will move the frog to the right.

#pond {
display: flex;
justify-content: flex-end;
}

Level 2

Use justify-content again to help these frogs get to their lilypads. Remember that this CSS property aligns items horizontally and accepts the following values:

flex-start: Items align to the left side of the container. flex-end: Items align to the right side of the container. center: Items align at the center of the container. space-between: Items display with equal spacing between them. space-around: Items display with equal spacing around them.

#pond {
display: flex;
justify-content: center;
}

Level 3

Help all three frogs find their lilypads just by using justify-content. This time, the lilypads have lots of space all around them.

If you find yourself forgetting the possible values for a property, you can click on the property name to view them. Try clicking on justify-content.

#pond {
display: flex;
justify-content: space-around;
}

Level 4

Now the lilypads on the edges have drifted to the shore, increasing the space between them. Use justify-content. This time, the lilypads have equal spacing between them.

#pond {
display: flex;
justify-content: space-between;
}

Level 5

Now use align-items to help the frogs get to the bottom of the pond. This CSS property aligns items vertically and accepts the following values:

flex-start: Items align to the top of the container. flex-end: Items align to the bottom of the container. center: Items align at the vertical center of the container. baseline: Items display at the baseline of the container. stretch: Items are stretched to fit the container.

#pond {
display: flex;
align-items: flex-end;
}

Level 6

Lead the frog to the center of the pond using a combination of justify-content and align-items.

#pond {
display: flex;
justify-content: center;
align-items: center;
}

Level 7

The frogs need to cross the pond again, this time for some lilypads with plenty of space around them. Use a combination of justify-content and align-items.

#pond {
display: flex;
justify-content: space-around;
align-items: flex-end;
}

Level 8

The frogs need to get in the same order as their lilypads using flex-direction. This CSS property defines the direction items are placed in the container, and accepts the following values:

row: Items are placed the same as the text direction. row-reverse: Items are placed opposite to the text direction. column: Items are placed top to bottom. column-reverse: Items are placed bottom to top.

#pond {
display: flex;
flex-direction: row-reverse;
}

Level 9

Help the frogs find their column of lilypads using flex-direction. This CSS property defines the direction items are placed in the container, and accepts the following values:

row: Items are placed the same as the text direction. row-reverse: Items are placed opposite to the text direction. column: Items are placed top to bottom. column-reverse: Items are placed bottom to top.

#pond {
display: flex;
flex-direction: column;
}

Level 10

Help the frogs get to their own lilypads. Although they seem close, it will take both flex-direction and justify-content to get them there.

Notice that when you set the direction to a reversed row or column, start and end are also reversed.

#pond {
display: flex;
flex-direction: row-reverse;
justify-content: flex-end;
}

Level 11

Help the frogs find their lilypads using flex-direction and justify-content.

Notice that when the flex direction is a column, justify-content changes to the vertical and align-items to the horizontal.

#pond {
display: flex;
flex-direction: column;
justify-content: flex-end;
}

Level 12

Help the frogs find their lilypads using flex-direction and justify-content.

#pond {
display: flex;
flex-direction: column-reverse;
justify-content: space-between;
}

Level 13

Help the frogs find their lilypads using flex-direction, justify-content, and align-items.

#pond {
display: flex;
flex-direction: row-reverse;
justify-content: center;
align-items: flex-end;
}

Level 14

Sometimes reversing the row or column order of a container is not enough. In these cases, we can apply the order property to individual items. By default, items have a value of 0, but we can use this property to also set it to a positive or negative integer value (-2, -1, 0, 1, 2).

Use the order property to reorder the frogs according to their lilypads.

#pond {
display: flex;
}

.yellow {
order: 1;
}

Level 15

Use the order property to send the red frog to his lilypad.

#pond {
display: flex;
}

.red {
order: -1;
}

Level 16

Another property you can apply to individual items is align-self. This property accepts the same values as align-items and its value for the specific item.

#pond {
display: flex;
align-items: flex-start;
}

.yellow {
align-self: flex-end;
}

Level 17

Combine order with align-self to help the frogs to their destinations.

#pond {
display: flex;
align-items: flex-start;
}

.yellow {
order: 1;
align-self: flex-end;
}

Level 18

Oh no! The frogs are all squeezed onto a single row of lilypads. Spread them out using the flex-wrap property, which accepts the following values:

nowrap: Every item is fit to a single line. wrap: Items wrap around to additional lines. wrap-reverse: Items wrap around to additional lines in reverse.

#pond {
display: flex;
flex-wrap: wrap;
}

Level 19

Help this army of frogs form three orderly columns using a combination of flex-direction and flex-wrap.

#pond {
display: flex;
flex-direction: column;
flex-wrap: wrap;
}

Level 20

The two properties flex-direction and flex-wrap are used so often together that the shorthand property flex-flow was created to combine them. This shorthand property accepts the value of the two properties separated by a space.

For example, you can use flex-flow: row wrap to set rows and wrap them.

Try using flex-flow to repeat the previous level.

#pond {
display: flex;
flex-flow: column wrap
}

Level 21

The frogs are spread all over the pond, but the lilypads are bunched at the top. You can use align-content to set how multiple lines are spaced apart from each other. This property takes the following values:

flex-start: Lines are packed at the top of the container. flex-end: Lines are packed at the bottom of the container. center: Lines are packed at the vertical center of the container. space-between: Lines display with equal spacing between them. space-around: Lines display with equal spacing around them. stretch: Lines are stretched to fit the container. This can be confusing, but align-content determines the spacing between lines, while align-items determines how the items as a whole are aligned within the container. When there is only one line, align-content has no effect.

#pond {
display: flex;
flex-wrap: wrap;
align-content: flex-start;
}

Level 22

Now the current has bunched the lilypads at the bottom. Use align-content to guide the frogs there.

#pond {
display: flex;
flex-wrap: wrap;
align-content: flex-end;
}

Level 23

The frogs have had a party, but it is time to go home. Use a combination of flex-direction and align-content to get them to their lilypads.

#pond {
display: flex;
flex-wrap: wrap;
flex-direction: column-reverse;
align-content: center;
}

Level 24

Bring the frogs home one last time by using the CSS properties you've learned:

justify-content:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

align-items:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

flex-direction:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

order:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

align-self:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

flex-wrap:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

flex-flow:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

align-content:Aligns flex items along the main axis.

flex-start (default) flex-end center space-between space-around space-evenly

#pond {
display: flex;
flex-wrap: wrap-reverse;
justify-content: center;
align-content: space-between;
flex-direction: column-reverse;
}

參考文件

  1. flexboxfroggy

Grid Garden 入門教學筆記 | 學習筆記

· 閱讀時間約 11 分鐘
kdchang

Grid(Grid Layout)是一種 CSS3 佈局模式,專門用來設計一維的彈性佈局,適用於水平或垂直排列元素,使網頁排版更加靈活且易於維護。

Grid Garden 透過花圃澆花遊戲化方式去介紹 Grid 使用方式

Level 1

Welcome to Grid Garden, where you write CSS code to grow your carrot garden! Water only the areas that have carrots by using the grid-column-start property.

For example, grid-column-start: 3; will water the area starting at the 3rd vertical grid line, which is another way of saying the 3rd vertical border from the left in the grid.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 3;
}

Level 2

Uh oh, looks like weeds are growing in the corner of your garden. Use grid-column-start to poison them. Note that the weeds start at the 5th vertical grid line.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#poison {
grid-column-start: 5;
}

Level 3

When grid-column-start is used alone, the grid item by default will span exactly one column. However, you can extend the item across multiple columns by adding the grid-column-end property.

Using grid-column-end, water all of your carrots while avoiding the dirt. We don't want to waste any water! Note that the carrots start at the 1st vertical grid line and end at the 4th.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 1;
grid-column-end: 4;
}

Level 4

When pairing grid-column-start and grid-column-end, you might assume that the end value has to be greater than the start value. But this turns out not the case!

Try setting grid-column-end to a value less than 5 to water your carrots.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 5;
grid-column-end: 2;
}

Level 5

If you want to count grid lines from the right instead of the left, you can give grid-column-start and grid-column-end negative values. For example, you can set it to -1 to specify the first grid line from the right.

Try setting grid-column-end to a negative value.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 1;
grid-column-end: -2;
}

Level 6

Now try setting grid-column-start to a negative value.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#poison {
grid-column-start: 4;
}

Level 7

Instead of defining a grid item based on the start and end positions of the grid lines, you can define it based on your desired column width using the span keyword. Keep in mind that span only works with positive values.

For example, water these carrots with the rule grid-column-end: span 2;.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 2;
grid-column-end: 4;
}

Level 8

Try using grid-column-end with the span keyword again to water your carrots.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 1;
grid-column-end: 6;
}

Level 9

You can also use the span keyword with grid-column-start to set your item's width relative to the end position.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 3;
grid-column-end: 6;
}

Level 10

Typing both grid-column-start and grid-column-end every time can get tiring. Fortunately, grid-column is a shorthand property that can accept both values at once, separated by a slash.

For example, grid-column: 2 / 4; will set the grid item to start on the 2nd vertical grid line and end on the 4th grid line.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column: 4/6;
}

Level 11

Try using grid-column to water these carrots. The span keyword also works with this shorthand property so give it a try!

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column: 2/5;
}

Level 12

One of the things that sets CSS grids apart from flexbox is that you can easily position items in two dimensions: columns and rows. grid-row-start works much like grid-column-start except along the vertical axis.

Use grid-row-start to water these carrots.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-row-start: 3;
}

Level 13

Now give the shorthand property grid-row a try.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-row: 3/6;
}

Level 14

Use grid-column and grid-row at the same time to set position in both dimensions.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#poison {
grid-column: 2;
grid-row: 5;
}

Level 15

You can also use grid-column and grid-row together to span larger areas within the grid. Give it a try!

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column: 2/6;
grid-row: 1/6;
}

Level 16

If typing out both grid-column and grid-row is too much for you, there's yet another shorthand for that. grid-area accepts four values separated by slashes: grid-row-start, grid-column-start, grid-row-end, followed by grid-column-end.

One example of this would be grid-area: 1 / 1 / 3 / 6;.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-area: 1 / 2 / 4 / 6;
}

Level 17

How about multiple items? You can overlap them without any trouble. Use grid-area to define a second area that covers all of the unwatered carrots.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water-1 {
grid-area: 1 / 4 / 6 / 5;
}

#water-2 {
grid-area: 2 / 3 / 5 / 6;
}

Level 18

If grid items aren't explicitly placed with grid-area, grid-column, grid-row, etc., they are automatically placed according to their order in the source code. We can override this using the order property, which is one of the advantages of grid over table-based layout.

By default, all grid items have an order of 0, but this can be set to any positive or negative value, similar to z-index.

Right now, the carrots in the second column are being poisoned and the weeds in the last column are being watered. Change the order value of the poison to fix this right away!

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

.water {
order: 0;
}

#poison {
order: 1;
}

Level 19

Now the water and poison are alternating, even though all of the weeds are at the start of your garden. Set the order of the poisons to remedy this.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

.water {
order: 0;
}

.poison {
order: -1;
}

Level 20

Up to this point, you've had your garden set up as a grid with five columns, each 20% of the full width, and five rows, each 20% of the full height.

This was done with the rules grid-template-columns: 20% 20% 20% 20% 20%; and grid-template-rows: 20% 20% 20% 20% 20%; Each rule has five values which create five columns, each set to 20% of the overall width of the garden.

But you can set the grid up however you like. Give grid-template-columns a new value to water your carrots. You'll want to set the width of the 1st column to be 50%.

#garden {
display: grid;
grid-template-columns: 50% 10% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column: 1;
grid-row: 1;
}

Level 21

Specifying a bunch of columns with identical widths can get tedious. Luckily there's a repeat function to help with that.

For example, we previously defined five 20% columns with the rule grid-template-columns: 20% 20% 20% 20% 20%;. This can be simplified as grid-template-columns: repeat(5, 20%);

Using grid-template-columns with the repeat function, create eight columns each with 12.5% width. This way you won't overwater your garden.

#garden {
display: grid;
grid-template-columns: repeat(1, 12.5%);
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column: 1;
grid-row: 1;
}

Level 22

grid-template-columns doesn't just accept values in percentages, but also length units like pixels and ems. You can even mix different units together.

Here, set three columns to 100px, 3em, and 40% respectively.

#garden {
display: grid;
grid-template-columns: 100px 3em 40%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

Level 23

Grid also introduces a new unit, the fractional fr. Each fr unit allocates one share of the available space. For example, if two elements are set to 1fr and 3fr respectively, the space is divided into 4 equal shares; the first element occupies 1/4 and the second element 3/4 of any leftover space.

Here, weeds make up the left 1/6 of your first row and carrots the remaining 5/6. Create two columns with these widths using fr units.

#garden {
display: grid;
grid-template-columns: 1fr 5fr;
grid-template-rows: 20% 20% 20% 20% 20%;
}

Level 24

When columns are set with pixels, percentages, or ems, any other columns set with fr will divvy up the space that's left over.

Here the carrots form a 50 pixel column on the left, and the weeds a 50 pixel column on the right. With grid-template-columns, create these two columns, and use fr to make three more columns that take up the remaining space in between.

#garden {
display: grid;
grid-template-columns: 50px 1fr 1fr 1fr 50px;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-area: 1 / 1 / 6 / 2;
}

#poison {
grid-area: 1 / 5 / 6 / 6;
}

Level 25

Now there is a 75 pixel column of weeds on the left side of your garden. 3/5 of the remaining space is growing carrots, while 2/5 has been overrun with weeds.

Use grid-template-columns with a combination of px and fr units to make the necessary columns.

#garden {
display: grid;
grid-template-columns: 75px 3fr 2fr;
grid-template-rows: 100%;
}

Level 26

grid-template-rows works much the same as grid-template-columns.

Use grid-template-rows to water all but the top 50 pixels of your garden. Note that the water is set to fill only your 5th row, so you'll need to create 5 rows in total.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 12.5px 12.5px 12.5px 12.5px;
}

#water {
grid-column: 1 / 6;
grid-row: 5 / 6;
}

Level 27

grid-template is a shorthand property that combines grid-template-rows and grid-template-columns.

For example, grid-template: 50% 50% / 200px; will create a grid with two rows that are 50% each, and one column that is 200 pixels wide.

Try using grid-template to water an area that includes the top 60% and left 200 pixels of your garden.

#garden {
display: grid;
grid-template: 60% / 200px;
}

#water {
grid-column: 1;
grid-row: 1;
}

Level 28

Your garden is looking great. Here you've left a 50 pixel path at the bottom of your garden and filled the rest with carrots.

Unfortunately, the left 20% of your carrots have been overrun with weeds. Use CSS grid one last time to treat your garden.

#garden {
display: grid;
grid-template: 1fr 50px / 1fr 4fr;
}

參考文件

  1. Playing CSS Grid Garden with Answers Explained

HTML & CSS 切版入門教學筆記 | 學習筆記

· 閱讀時間約 3 分鐘
kdchang

HTML(HyperText Markup Language)是網頁的基礎結構,透過標籤(Tag)定義不同的內容與結構。

1.1 常見標籤

  • <!DOCTYPE html>:宣告 HTML 文件類型。
  • <html>:HTML 文件的根標籤。
  • <head>:包含頁面設定、SEO 資訊、CSS 連結等。
  • <title>:設定網頁標題。
  • <body>:放置頁面可見內容。
  • <h1> ~ <h6>:標題。
  • <p>:段落。
  • <a>:超連結。
  • <img>:圖片。
  • <ul><ol><li>:無序與有序列表。
  • <div>:區塊。
  • <span>:行內元素。
  • <table><tr><td>:表格。

1.2 HTML5 新增語意標籤

  • <header>:頁首。
  • <nav>:導航。
  • <section>:區段。
  • <article>:獨立內容。
  • <aside>:側邊欄。
  • <footer>:頁尾。

2. CSS 基礎概念

CSS(Cascading Style Sheets)用於設計與美化 HTML 元素。

2.1 CSS 引入方式

  • 內嵌樣式(Inline Style):直接寫在 HTML 標籤內,例如:
    <p style="color: red; font-size: 16px;">這是一段文字</p>
  • 內部樣式(Internal Style):寫在 <style> 標籤內,例如:
    <style>
    p { color: blue; font-size: 18px; }
    </style>
  • 外部樣式(External Style):將 CSS 放入 .css 文件中,再用 <link> 連結,例如:
    <link rel="stylesheet" href="styles.css">

2.2 CSS 選擇器

  • 標籤選擇器:影響所有相同標籤,例如:
    p { color: green; }
  • 類別選擇器(Class):適用於多個元素,例如:
    .box { background-color: yellow; }
    <div class="box">內容</div>
  • ID 選擇器:適用於單一元素,例如:
    #header { font-size: 24px; }
    <h1 id="header">標題</h1>
  • 後代選擇器:選擇特定層級內的元素,例如:
    div p { color: blue; }

2.3 盒模型(Box Model)

盒模型包含四個部分:

  1. Content(內容區域)。
  2. Padding(內距,內容與邊框之間的距離)。
  3. Border(邊框)。
  4. Margin(外距,與其他元素的距離)。

範例:

.box {
width: 200px;
height: 100px;
padding: 20px;
border: 2px solid black;
margin: 10px;
}

3. 常見版型切版技巧

3.1 Flexbox 佈局

Flexbox 用於彈性排列子元素。

.container {
display: flex;
justify-content: space-between;
align-items: center;
}

3.2 Grid 佈局

Grid 提供更強大的網格系統。

.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}

3.3 響應式設計(RWD)

使用 @media 來適應不同螢幕尺寸。

@media (max-width: 768px) {
.container {
flex-direction: column;
}
}

4. 實戰案例:基本網頁切版

HTML

<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>簡單網頁</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>我的網站</h1>
</header>
<nav>
<ul>
<li><a href="#">首頁</a></li>
<li><a href="#">關於</a></li>
<li><a href="#">聯絡</a></li>
</ul>
</nav>
<section class="content">
<p>這是一個簡單的 HTML & CSS 切版示範。</p>
</section>
</body>
</html>

CSS

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background: #333;
color: white;
text-align: center;
padding: 10px;
}
nav ul {
list-style: none;
display: flex;
justify-content: center;
padding: 0;
}
nav ul li {
margin: 0 15px;
}
nav a {
text-decoration: none;
color: black;
}
.content {
max-width: 800px;
margin: auto;
padding: 20px;
}

5. 總結

透過學習 HTML 與 CSS,可以建立結構清晰、外觀美觀的網頁。建議多加練習不同的切版方式,如 Flexbox 和 Grid,並運用 RWD 技巧來提升適應性,讓網站在不同裝置上都能有良好的呈現效果。

SASS 語法介紹入門教學筆記 | 學習筆記

· 閱讀時間約 5 分鐘
kdchang

SASS(Syntactically Awesome Style Sheets)是一種 CSS 預處理器,旨在提升 CSS 的功能性,讓開發者能夠以更加靈活和高效的方式編寫樣式表。它提供了許多比 CSS 更強大的功能,例如變數、巢狀規則、混合(mixins)、繼承等。SASS 語法有兩種主要形式:一種是較為常見的 SCSS(Sassy CSS),另一種則是 SASS,本文將主要介紹 SASS 語法。

與 SCSS 不同,SASS 語法採用的是縮排語法,即不使用大括號和分號,而是利用縮排來結構化程式碼。這種語法更簡潔,對於習慣 Python 等語言的開發者來說,學習曲線較為平滑。

安裝與設置

要開始使用 SASS,首先需要安裝 SASS 編譯器。最常見的安裝方式是透過 Node.js 的 npm(Node Package Manager)。請按照以下步驟進行安裝:

  1. 確保已經安裝了 Node.js 和 npm。

  2. 打開終端機,並在專案資料夾中執行以下命令來安裝 SASS:

    npm install -g sass
  3. 安裝完成後,可以通過命令行執行 SASS 編譯命令:

    sass input.sass output.css

這樣,input.sass 就會被編譯為標準的 output.css 檔案。

SASS 語法介紹

1. 變數(Variables)

SASS 的變數功能讓開發者可以將顏色、字體大小、間距等常用值儲存在變數中,這樣能夠提高樣式的可重用性,並讓程式碼更具維護性。在 SASS 中,變數以 $ 符號開頭。

$primary-color: #3498db
$font-size: 16px

body
font-size: $font-size
color: $primary-color

在這段程式碼中,我們定義了 $primary-color$font-size 兩個變數,並將其應用於 body 樣式中。這樣,只需要修改變數的值,即可全局更新相應的樣式。

2. 巢狀規則(Nesting)

SASS 支援巢狀規則,這樣可以讓樣式更加結構化,並且簡化對於子元素樣式的編寫。SASS 使用縮排來表示層級關係,這一點與傳統的 CSS 需要寫出完整選擇器有所不同。

nav
background-color: #333
ul
list-style-type: none
padding: 0
li
display: inline-block
a
color: white
text-decoration: none

這段程式碼會被編譯為:

nav {
background-color: #333;
}
nav ul {
list-style-type: none;
padding: 0;
}
nav li {
display: inline-block;
}
nav a {
color: white;
text-decoration: none;
}

這樣的寫法可以避免寫重複的選擇器,並且清晰地表現出元素之間的層級結構。

3. 混合(Mixins)

混合是 SASS 中一個非常有用的功能,它可以將一段可重用的樣式封裝成一個混合,並且可以接受參數,實現樣式的動態應用。混合類似於函數,能夠在不同地方重複使用。

=mixin border-radius($radius)
-webkit-border-radius: $radius
-moz-border-radius: $radius
border-radius: $radius

.box
@include border-radius(10px)

在這段程式碼中,我們定義了一個名為 border-radius 的混合,接受一個 $radius 參數,用來設置元素的邊框圓角。然後,我們在 .box 中使用 @include 引入這個混合,並傳遞具體的參數。這樣,當需要改變邊框圓角的樣式時,只需要修改混合的參數,而不需要在多個地方重複編寫。

4. 繼承(Inheritance)

SASS 提供了繼承功能,使得一個選擇器可以繼承另一個選擇器的樣式。這有助於減少樣式重複,並保持程式碼的整潔性。SASS 使用 @extend 指令來實現繼承。

%button-base
padding: 10px 15px
background-color: #3498db
color: white
border: none
border-radius: 5px

.button-primary
@extend %button-base
background-color: #1abc9c

.button-secondary
@extend %button-base
background-color: #f39c12

在這段程式碼中,我們定義了一個 %button-base 共享樣式,然後讓 .button-primary.button-secondary 繼承這些樣式,並根據需要進行自定義修改。使用繼承的方式可以減少代碼重複,提高樣式的可維護性。

5. 條件語句(Conditionals)

SASS 支援條件語句,這讓我們可以根據某些條件選擇性地應用不同的樣式。這樣可以使樣式表更具動態性,根據不同情境調整顯示效果。

$theme: light

body
@if $theme == light
background-color: #fff
color: #333
@else
background-color: #333
color: #fff

這段程式碼中,根據變數 $theme 的值,條件地設定 body 的背景顏色和文字顏色。如果 $themelight,則使用淺色背景和深色文字;否則,使用深色背景和淺色文字。

6. 循環(Loops)

SASS 還支援循環語句,這在需要根據某些條件自動生成多個樣式時非常有用。SASS 的循環可以遍歷一個列表,並生成對應的樣式。

$colors: red, green, blue

@each $color in $colors
.#{$color}-box
background-color: $color

在這段程式碼中,@each 循環將遍歷 $colors 列表,並為每個顏色生成一個相應的類別 .red-box.green-box.blue-box,並將其背景顏色設置為對應的顏色。

總結

SASS 的 SASS 語法是一種簡潔且強大的 CSS 編寫方式,通過簡單的縮排結構,讓開發者能夠更有效率地編寫和維護樣式。SASS 提供的變數、巢狀規則、混合、繼承等功能,能夠使樣式更加模組化、動態化,並大大減少冗餘代碼。學會 SASS 語法後,你可以更靈活地處理大型專案中的 CSS,提升工作效率。如果你還沒有開始使用 SASS,不妨從這些基礎語法開始,體驗它帶來的便利。

SCSS 介紹入門教學筆記 | 學習筆記

· 閱讀時間約 4 分鐘
kdchang

SASS(Syntactically Awesome Stylesheets)是一種 CSS 預處理器(CSS Preprocessor),它擴展了 CSS 的功能,使樣式表更具可讀性、模組化和可維護性。SASS 允許使用變數、巢狀(Nesting)、混入(Mixin)、繼承(Extend)等進階特性,讓開發者能更有效率地管理 CSS。

SASS 有兩種語法:

  1. SCSS(Sassy CSS):與傳統 CSS 語法相似,使用 {}; 來區分樣式,擴展性強且相容 CSS。
  2. SASS(縮排語法):省略 {};,使用縮排來表示層級關係,簡潔但較不常用。

目前,SCSS 語法較受歡迎,因此本文主要以 SCSS 為主進行介紹。


二、SASS 的優勢

使用 SASS 的主要優勢包括:

  1. 可維護性:透過模組化的結構管理樣式,避免冗長且難以維護的 CSS。
  2. 變數(Variables):可定義全站共用的變數,例如顏色、字體大小等,提高一致性。
  3. 巢狀結構(Nesting):讓樣式更具層次感,避免重複選擇器。
  4. 混入(Mixin):類似函式的概念,可重複使用樣式區塊,減少冗餘。
  5. 繼承(Extend):透過 @extend 共享樣式,減少重複編寫的代碼。
  6. 函式(Functions):內建函式如 lighten()darken() 可動態調整顏色,提高設計靈活性。

三、安裝與使用 SASS

1. 透過 npm 安裝

如果使用 Node.js,可透過 npm 安裝 SASS:

npm install -g sass

安裝後,可使用以下指令將 SCSS 轉譯為 CSS:

sass input.scss output.css

可使用 --watch 讓 SASS 自動監聽檔案變化並即時編譯:

sass --watch input.scss:output.css

2. 透過 CDN 使用

雖然 SASS 本身無法直接在瀏覽器運行,但可透過一些線上工具(如 CodePen)編寫 SCSS,並自動編譯成 CSS 進行預覽。


四、SASS 基礎語法

1. 變數(Variables)

SASS 允許使用變數來存儲顏色、字體大小、間距等常數,使樣式更具一致性。

$primary-color: #3498db;
$font-size: 16px;

body {
color: $primary-color;
font-size: $font-size;
}

2. 巢狀結構(Nesting)

在 CSS 中,我們通常需要重複撰寫父選擇器,但在 SASS 中可直接巢狀編寫,提高可讀性。

nav {
background: #333;
ul {
list-style: none;
li {
display: inline-block;
a {
color: white;
text-decoration: none;
}
}
}
}

這段 SCSS 會編譯成以下 CSS:

nav {
background: #333;
}
nav ul {
list-style: none;
}
nav ul li {
display: inline-block;
}
nav ul li a {
color: white;
text-decoration: none;
}

3. 混入(Mixin)

Mixin 可定義可重複使用的樣式區塊,並可接受參數,使樣式更加靈活。

@mixin button-style($bg-color) {
background-color: $bg-color;
color: white;
padding: 10px 15px;
border-radius: 5px;
}

.btn-primary {
@include button-style(#3498db);
}

.btn-secondary {
@include button-style(#2ecc71);
}

編譯後的 CSS 為:

.btn-primary {
background-color: #3498db;
color: white;
padding: 10px 15px;
border-radius: 5px;
}

.btn-secondary {
background-color: #2ecc71;
color: white;
padding: 10px 15px;
border-radius: 5px;
}

4. 繼承(Extend)

@extend 允許一個選擇器繼承另一個選擇器的樣式,避免重複撰寫代碼。

.message {
padding: 10px;
border-radius: 5px;
}

.success {
@extend .message;
background: #2ecc71;
}

.error {
@extend .message;
background: #e74c3c;
}

編譯後的 CSS:

.message, .success, .error {
padding: 10px;
border-radius: 5px;
}

.success {
background: #2ecc71;
}

.error {
background: #e74c3c;
}

5. 運算與函式

SASS 允許在樣式中進行運算,使數值調整更加靈活。

$base-size: 16px;

h1 {
font-size: $base-size * 2;
}

h2 {
font-size: $base-size * 1.5;
}

此外,SASS 內建許多函式,例如 darken()lighten() 可用來調整顏色:

$primary-color: #3498db;

button {
background: $primary-color;
&:hover {
background: darken($primary-color, 10%);
}
}

編譯後的 CSS:

button {
background: #3498db;
}
button:hover {
background: #217dbb;
}

五、SASS 進階技巧

1. 分割檔案

SASS 允許將樣式拆分成多個檔案,並透過 @import@use 來管理,提升可維護性。

// _variables.scss
$primary-color: #3498db;
$font-size: 16px;

// main.scss
@import 'variables';

body {
color: $primary-color;
font-size: $font-size;
}

2. 使用 @use

@use@import 的改進版,能避免變數命名衝突,推薦使用:

@use 'variables' as v;

body {
color: v.$primary-color;
font-size: v.$font-size;
}

六、結論

SASS 是一種強大的 CSS 預處理器,它提供變數、巢狀、Mixin、繼承等功能,使樣式管理更加高效與模組化。透過 SASS,開發者可以撰寫更具結構性、可讀性和可維護性的 CSS。

對於前端開發者來說,掌握 SASS 不僅能提升開發效率,還能讓專案的樣式管理更加清晰。在實際專案中,建議將樣式模組化,並善用變數與 Mixin,以確保程式碼的可重用性與一致性。

LESS 入門教學筆記 | 學習筆記

· 閱讀時間約 4 分鐘
kdchang

前言

LESS(Leaner Style Sheets)是一種 CSS 預處理器,它在 CSS 的基礎上加入了變數、嵌套、混合(Mixins)、函式等功能,使樣式表的管理更加靈活且易於維護。LESS 文件最終會被編譯成標準的 CSS,並可在瀏覽器或 Node.js 環境中使用。


1. 安裝與使用

LESS 可以透過以下幾種方式使用:

1.1 透過 LESS.js 在瀏覽器中運行

這種方式適合開發環境,但不建議在正式環境中使用,因為它會在瀏覽器端進行編譯,影響效能。

<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LESS 測試</title>
<link rel="stylesheet/less" type="text/css" href="styles.less">
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/4.1.1/less.min.js"></script>
</head>
<body>
<h1>Hello LESS!</h1>
</body>
</html>

1.2 透過 Node.js 編譯 LESS

如果你希望在開發環境中預先編譯 LESS,則可以使用 npm 安裝 LESS:

npm install -g less

然後使用以下指令將 .less 文件編譯為 .css

lessc styles.less styles.css

這樣就能夠將 LESS 轉換為 CSS,並直接在 HTML 中引用 styles.css


2. LESS 的基本語法

2.1 變數(Variables)

LESS 允許使用變數來儲存顏色、字型大小、間距等值,方便統一管理樣式。

@primary-color: #3498db;
@font-size: 16px;

body {
color: @primary-color;
font-size: @font-size;
}

2.2 嵌套(Nesting)

LESS 允許使用嵌套的方式來撰寫 CSS,這樣可以清楚地表示層級關係。

nav {
background-color: #333;
ul {
list-style: none;
li {
display: inline-block;
a {
text-decoration: none;
color: white;
}
}
}
}

編譯後的 CSS:

nav {
background-color: #333;
}
nav ul {
list-style: none;
}
nav ul li {
display: inline-block;
}
nav ul li a {
text-decoration: none;
color: white;
}

2.3 混合(Mixins)

混合(Mixin)類似於函式,可以定義一組樣式,並在多個地方重複使用。

.border-radius(@radius) {
border-radius: @radius;
}

.button {
background-color: @primary-color;
.border-radius(5px);
}

編譯後的 CSS:

.button {
background-color: #3498db;
border-radius: 5px;
}

2.4 運算(Operations)

LESS 支援數學運算,可以用來計算尺寸、顏色等。

@base-size: 10px;

.box {
width: @base-size * 5;
height: @base-size * 3;
padding: @base-size + 5px;
}

編譯後的 CSS:

.box {
width: 50px;
height: 30px;
padding: 15px;
}

2.5 繼承(Extend)

LESS 提供 extend 功能,允許一個選擇器繼承另一個選擇器的樣式。

.message {
padding: 10px;
border: 1px solid #ddd;
}

.success {
&:extend(.message);
background-color: #dff0d8;
}

編譯後的 CSS:

.message,
.success {
padding: 10px;
border: 1px solid #ddd;
}
.success {
background-color: #dff0d8;
}

3. 進階功能

3.1 運用函式(Functions)

LESS 提供許多內建函式,例如 lighten()darken()fadeout() 等來調整顏色透明度、亮度等。

@main-color: #3498db;

.button {
background-color: @main-color;
border: 1px solid darken(@main-color, 10%);
color: lighten(@main-color, 20%);
}

編譯後的 CSS:

.button {
background-color: #3498db;
border: 1px solid #217dbb;
color: #5dade2;
}

3.2 迴圈(Loops)

LESS 允許使用 each() 來迭代陣列,或使用 for 來執行迴圈。

@colors: red, green, blue;

.each(@colors, {
.box-@{value} {
background-color: @value;
}
});

編譯後的 CSS:

.box-red {
background-color: red;
}
.box-green {
background-color: green;
}
.box-blue {
background-color: blue;
}

3.3 延遲運算(Lazy Evaluation)

LESS 變數的值在運算時才會解析,因此可以動態變更變數內容。

@theme-color: @primary-color;

.button {
background-color: @theme-color;
}

這樣如果稍後更改 @primary-color@theme-color 也會自動更新。


4. 結論

LESS 透過變數、嵌套、混合、運算等功能,大大提升了 CSS 的可維護性與開發效率。建議開發者透過 Node.js 進行 LESS 編譯,避免在瀏覽器端執行影響效能。透過 LESS,樣式表變得更具結構化,讓前端開發更為靈活高效。