| 類型 | @規則 | 用途 | 語法類型 |
|---|---|---|---|
| 常規規則(語句級) | @charset | 聲明樣式表字符編碼 | @charset "UTF-8"; |
@import | 引入外部樣式表 | @import url("base.css"); | |
@namespace | XML/HTML 命名空間 | @namespace svg url(...); | |
| 嵌套規則(塊級) | @media | 條件樣式(響應式、打印) | @media (max-width: 768px) { } |
@supports | 特性檢測 | @supports (display: grid) { } | |
@keyframes | 動畫關鍵幂 | @keyframes fadeIn { from{opacity:0} to{opacity:1} } | |
@font-face | 自定義字體 | @font-face { font-family: 'F'; src: url(f.woff2); } | |
@page | 打印頁面樣式 | @page :first { margin: 2cm; } | |
@document | 特定文檔樣式 | @document url("...") { } | |
@counter-style | 自定義計數器 | @counter-style custom { system: cyclic; symbols: "★"; } | |
@property | 註冊自定義屬性 (Houdini) | @property --x { syntax: " |
@charset "UTF-8"; /* 僅 ASCII 兼容編碼需聲明,UTF-8 建議顯式聲明 */
@import "reset.css"; /* @charset 之後 */
HTTP Header Content-Type: text/css; charset=utf-8 優先級高於 @charset。
@import "layout.css";
@import "theme.css" screen; /* 媒體條件 */
/* ⚠️ 性能警告:每個 @import 產生額外 HTTP 請求,阻塞渲染 */
/* 建議:構建時合併(Webpack/Rollup/Vite),或用 */
@namespace url(https://www.w3.org/1999/xhtml); /* XHTML 默認 */
@namespace svg url(https://www.w3.org/2000/svg); /* SVG 元素選擇器 */
svg|circle { fill: red; } /* 僅匹配 SVG circle */
/* 斷點 */
@media (min-width: 768px) { .container { max-width: 720px; } }
/* 邏輯運算 */
@media (min-width: 768px) and (max-width: 1023px) { }
@media (orientation: landscape), (min-width: 1024px) { } /* or */
/* 打印專用 */
@media print {
.no-print { display: none; }
.page-break { page-break-before: always; }
a::after { content: " (" attr(href) ")"; }
}
/* 單條件 */
@supports (display: grid) {
.layout { display: grid; }
}
/* 多條件 AND/OR/NOT */
@supports (display: flex) and (not (display: grid)) {
.layout { display: flex; } /* Grid 不支援時回退 */
}
/* JS 配合 */
if (CSS.supports('display', 'grid')) { /* ... */ }
@keyframes pulse {
0% { transform: scale(1); background: #007bff; }
50% { transform: scale(1.05); background: #00d4ff; }
100% { transform: scale(1); background: #007bff; }
}
.pulse { animation: pulse 2s ease-in-out infinite; }
@font-face {
font-family: 'CustomFont';
src:
url('font.woff2') format('woff2'),
url('font.woff') format('woff');
font-weight: 400 700; /* 變量字體範圍 */
font-style: normal;
font-display: swap; /* 關鍵:避免 FOIT */
unicode-range: U+4E00-9FFF; /* 中文區塊子集化 */
}
@page {
margin: 2cm;
size: A4 landscape;
}
@page :first { margin-top: 3cm; } /* 首頁 */
@page :left { margin-right: 3cm; } /* 左頁 */
@page :right { margin-left: 3cm; } /* 右頁 */
@page :blank { @top-center { content: "Confidential"; } }
@document
url("https://example.com/admin"),
url-prefix("https://example.com/blog/"),
domain("example.com"),
regexp("https:.*") {
body { font-size: 110%; }
}
⚠️ @document 已從標準移除,僅 Firefox 支援(需 @-moz-document),不推薦生產使用。
@charset、@import:構建時處理,產物無此規則@media、@supports:運行時響應環境/能力,核心響應式手段@keyframes、@font-face:聲明式資源定義,瀏覽器原生優化@page:打印樣式專用,不可或缺@property、@counter-style:Houdini 低級 API,前沿探索CSS 導航欄製作實戰:Flexbox、下拉動畫、響應式折疊