CSS 引入方式直接決定樣式的作用範圍、優先級、可維護性與性能。本文系統對比行內樣式、內嵌樣式表、外部鏈接三大方式,並給出現代前端工程化建議。
| 維度 | 行內樣式 (Inline) | 內嵌樣式表 (Embedded) | 外部鏈接 (External) |
|---|---|---|---|
| 語法 | <div style="..."> | <style>...</style> | <link rel="stylesheet" href="..."> |
| 位置 | 任意 HTML 標籤 | <head> 內 | <head> 內 |
| 優先級 | 最高 (1000) | 正常 (0100) | 正常 (0100) |
| 作用域 | 單一元素 | 當前頁面 | 全站/多頁面 |
| 復用性 | 無 | 單頁復用 | 跨頁面/項目復用 |
| 緩存 | 無 (隨 HTML) | 無 (隨 HTML) | 強緩存/協商緩存 |
| 並行下載 | 無 | 無 | ✅ 並行下載 |
| 維護性 | 極差 | 一般 | 優秀 |
| CSP 友好 | ❌ 違反 'unsafe-inline' | ❌ 違反 'unsafe-inline' | ✅ 合規 |
| 適用場景 | 動態計算、郵件、原型 | 關鍵 CSS、單頁應用、演示 | **生產環境主流方案** |
<p style="color: red; font-size: 16px; line-height: 1.5;">紅色段落</p>
<body> 內元素**,<head>、<title> 等不可用style="background: url('img.jpg');":hover, ::before 等)@media)el.style.color = 'red' (駝峰命名: fontSize, backgroundColor)<head>
<style type="text/css">
/* HTML5 可省略 type */
.highlight { color: red; font-weight: bold; }
@media (max-width: 768px) { .hide-mobile { display: none; } }
</style>
</head>
<!-- --> 中防止顯示為文本 (現代瀏覽器無需)<head>
<!-- 基礎用法 -->
<link rel="stylesheet" href="/css/main.css">
<!-- 帶媒體查詢 -->
<link rel="stylesheet" href="/css/print.css" media="print">
<link rel="stylesheet" href="/css/mobile.css" media="(max-width: 768px)">
<!-- 備選樣式表 (換膚) -->
<link rel="alternate stylesheet" title="Dark Mode" href="/css/dark.css">
<link rel="stylesheet" title="Default" href="/css/light.css">
<!-- 預加載關鍵 CSS -->
<link rel="preload" as="style" href="/css/critical.css" onload="this.rel='stylesheet'">
</head>
rel="stylesheet":標準樣式表rel="alternate stylesheet":備選樣式,需 JS 切換 disabled 屬性啟用media:媒體類型/查詢,匹配時才下載應用import './style.css' 生成 <link><!-- HTML -->
<div id="box" class="box" style="color: green;">文字顏色是?</div>
<style>
/* 外部/內嵌 CSS */
#box { color: blue !important; } /* 0100 + !important = 最高 */
.box { color: red; } /* 0010 */
div { color: black; } /* 0001 */
</style>
結果:藍色 (ID + !important 勝出)。
去掉 !important:綠色 (行內 1000 > ID 0100)。
去掉行內:藍色 (ID 0100 > 類 0010)。
<style>),其餘異步加載:root { --primary: #007bff; } + [data-theme="dark"] 替代多套樣式表切換Content-Security-Policy: style-src 'self' 'nonce-xxx' 僅允許外部鏈接<head> 大量內嵌樣式 (超過 14KB 關鍵 CSS 閾值)@import 在 HTML <style> 中導入外部 CSS (串行阻塞)<link> 作為主流引入方式Cache-Control: max-age=31536000, immutable) + 文件名哈希