跳轉到

建立 2025-02-25 更新 2026-09-11

CSS 函式(Functions)

函式出現在屬性值裡,用來算長度、夾值、取色、讀 HTML 屬性。與 JS 函式不同,它們在樣式計算時求值。

calc()

可混單位;+ - 兩側要有空白* / 可省略空白但除數必須是數字。

.main {
  width: calc(100% - 2 * var(--gutter));
  min-height: calc(100dvh - var(--nav-h));
}

無效例子:calc(50% * 2px)(兩個都帶單位相乘)。相對的,calc(50% * 2) 可以。

min()max()clamp()

.container {
  width: min(100% - 2rem, 72rem); /* 寧窄勿溢 */
}

.sidebar {
  width: max(16rem, 28%); /* 至少 16rem */
}

h1 {
  font-size: clamp(1.5rem, 1rem + 2vw, 2.5rem);
}

clamp(min, preferred, max) 等於 max(min, min(preferred, max))。字級、內距、容器寬都適合。

var()

變數。可巢狀:var(--btn-bg, var(--brand))

顏色函式

.chip {
  background: rgb(38 77 228 / 12%);
  color: oklch(45% 0.15 264);
  border-color: color-mix(in srgb, currentColor 25%, transparent);
}

hsl()hwb()color-mix() 適合做 hover 時「比品牌色再暗一點」而不另開變數。

Grid 相關

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
}

repeat()minmax() 常與 min() 套在一起,避免 minmax 的最小值大於容器。

attr()

主要搭配 content,把 HTML 屬性顯示成文字:

<button class="tip" data-hint="儲存後無法復原">刪除</button>
.tip::after {
  content: "(" attr(data-hint) ")";
  font-size: 0.85em;
  color: #666;
}

現代瀏覽器開始支援把 attr() 用在其他屬性,但相容性仍請查表。重要訊息不要只放在 content 裡。

其他實用函式

函式 用途
url() 圖片、字體、SVG
image-set() 依解析度選圖
counter() / counters() 自訂編號
round() / abs() / sign() 數值處理(新,需確認支援)
env(safe-area-inset-bottom) 瀏海與 Home 指示條
.tabbar {
  padding-bottom: calc(0.5rem + env(safe-area-inset-bottom, 0px));
}

總結

函式 一句话
calc() 混單位運算
min / max / clamp 設上限下限
var 讀自訂屬性
color-mix / rgb / oklch 顏色
repeat / minmax Grid 軌道
attr 把屬性變成內容
env 安全區

到這裡,CSS 日常會用到的核心已經串起來了。建議回到 簡介 的練習:做一張有圓角、陰影、hover 過渡的卡片,並用變數管理顏色。