| 場景 | 推薦方式 | 理由 |
|---|---|---|
| 多頁共用樣式 | 外部連結 <link> | 緩存複用、單點維護、減少體積 |
| 單頁獨有樣式 | 內部 <style> | 避免額外請求、首屏內聯關鍵 CSS |
| 極少量局部樣式 | 內嵌 style="" | 零請求、最高優先級、動態值注入 |
瀏覽器解析順序:內嵌 > 內部 > 外部/導入(同層級後定義勝出)
/* 外部 base.css */
h3 { color: red; text-align: left; font-size: 8pt; }
/* 內部 style */
h3 { text-align: right; font-size: 20pt; }
/* 內嵌 */
<h3 style="color: blue;">結果:藍字、右對齊、20pt</h3>
歷史操作:DW 面板定義 → 複製到 .css → 手動 link 引入
現代流程:
.highlight { background: #ffc; } /* 色塊 */
.text-bg-img { background: url(texture.png); -webkit-background-clip: text; color: transparent; }
body {
background: url(bg.jpg) center/cover fixed;
background-attachment: fixed; /* 關鍵:背景相對視口固定 */
}
.loose { letter-spacing: 0.1em; } /* 字符間距 */
.tight { letter-spacing: -0.05em; } /* 緊湊標題 */
.fancy-text {
text-decoration: underline overline line-through;
/* blink 已棄用,勿用 */
}
p { text-indent: 2em; } /* 2 個字符寬度,完美適配響應式字體 */
td { padding: 0 10px; } /* 左右各 10px,上下 0 */
/* 替代老式 margin hack */
.custom-border {
border-style: solid;
border-width: 1px 0 0 2px; /* 上右下左 */
border-color: #00f transparent transparent #0f0;
}
/* reset.css */
* { margin: 0; padding: 0; box-sizing: border-box; }
/* variables.css */
:root { --primary: #007bff; --spacing: 1rem; }
/* components/btn.css */
.btn { padding: var(--spacing); background: var(--primary); }
現代做法:直接編寫類名,配合 Utility-first 框架(Tailwind)或 CSS Modules。
/*
開發環境保留:說明用途、依賴、TODO
生產環境:cssnano 移除註釋(保留 @license)
*/
.logo {
width: 200px; height: 60px;
background: url(logo.svg) center/contain no-repeat;
text-indent: -9999px; /* 隱藏文字,SEO 友好 */
}
html { font-size: clamp(16px, 2vw, 24px); } /* 視口自適應 */
* { box-sizing: border-box; } /* 統一盒模型:width = content + padding + border */
/* IE6 怪異模式無需支援 */
/* Flex 版 - 現代標準 */
.center { display: flex; justify-content: center; align-items: center; }
/* Grid 版 - 兩行代碼 */
.center { display: grid; place-items: center; }
/* 兼容舊版 - 絕對定位 + transform */
.center { position: relative; }
.center::before { content: ''; display: inline-block; height: 100%; vertical-align: middle; }
.center > * { display: inline-block; vertical-align: middle; }
!important → ✅ 提升具體性或重構架構.a .b .c .d → ✅ BEM 扁平化 .a__drem + 關鍵處 em這 14 個案例覆蓋 90% 日常 CSS 需求,掌握核心模式比記憶具體代碼更有價值。