CSS 早已不是單純的「樣式表」,attr()、counter()、calc() 三大函數讓 CSS 具備了數據讀取、自動編號、數學運算能力,能替代大量 JavaScript 邏輯。本文深度解析三者語法、瀏覽器支援度與實戰場景。
attr():讀取 HTML 屬性值進 CSScontent: attr(屬性名 [, 類型?, 回退值?]);
/* 類型:string | url | integer | number | length | angle | time | frequency | color */
/* CSS Values Level 3 擴展了類型支援,但瀏覽器實現多僅支援 string */
@media print {
a[href]::after {
content: ' (鏈接: ' attr(href) ') ';
font-size: 0.8em;
color: #666;
}
}
[data-tooltip] {
position: relative;
}
[data-tooltip]::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%; left: 50%;
transform: translateX(-50%);
padding: 4px 8px;
background: #333; color: #fff;
border-radius: 4px;
white-space: nowrap;
opacity: 0; pointer-events: none;
transition: opacity 0.2s;
}
[data-tooltip]:hover::after { opacity: 1; }
.badge::before { content: attr(data-count); }
<span class="badge" data-count="99+"></span>
counter():CSS 自動編號系統counter-reset: <名稱> [<初始值>] — 建立/重置計數器counter-increment: <名稱> [<增量>] — 遞增計數器counter(<名稱> [, <列表樣式>]) — 取值(用於 content)body { counter-reset: chapter; }
h2::before {
counter-increment: chapter;
content: '第 ' counter(chapter) ' 章 ';
}
h2 { counter-reset: section; }
h3::before {
counter-increment: section;
content: counter(chapter) '.' counter(section) ' ';
}
輸出:
第 1 章
1.1 節標題
1.2 節標題
第 2 章
2.1 節標題...
counters()ol { counter-reset: item; list-style: none; }
li::before {
counter-increment: item;
content: counters(item, '.') ' '; /* 自動處理多層嵌套 */
}
calc():CSS 內建數學運算+ - * /(* 至少一邊無單位,/ 右邊必須無單位)calc(100% - 80px)、calc(50vw - 2em)calc(100% / 3 - calc(1em * 2)).sidebar { width: 260px; flex-shrink: 0; }
.main { width: calc(100% - 260px); }
.modal {
position: fixed; top: 50%; left: 50%;
transform: translate(-50%, -50%);
/* 或不使用 transform: */
width: calc(100% - 40px); max-width: 600px;
height: calc(100% - 40px); max-height: 90vh;
margin: auto; top: 0; right: 0; bottom: 0; left: 0;
}
html { font-size: calc(16px + 0.5vw); } /* 16px 基礎 + 視口寬度微調 */
| 函數 | Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|---|
attr() (string) | 2+ | 1+ | 3.1+ | 12+ | 8+ |
counter() | 1+ | 1+ | 3+ | 12+ | 8+ |
calc() | 26+ | 16+ | 7+ | 12+ | 9+ (部分 Bug) |
attr():數據駐留在 HTML、需在偽元素/列印樣式中顯示時counter():文檔結構化編號、列表自動序號、嵌套章節calc():混合單位佈局、流體計算、避免 JS 佈局抖動這三個函數將 CSS 從「聲明式樣式」推向「聲明式邏輯」,善用它們,能大幅減少 JavaScript 佈局代碼,讓樣式表更具表達力。