直接在標籤上使用 style 屬性,優先級最高,但難維護。
<p style="color: #333; font-size: 16px;">灰色段落文字</p>
<h1 style="color: rgb(255, 0, 0);">紅色標題</h1>
在 <head> 中定義 <style>,針對當前頁面生效。
<head>
<style>
.text-primary { color: #007bff; }
.text-danger { color: #dc3545; }
h2 { color: #28a745; }
</style>
</head>
<body>
<p class="text-primary">藍色文字</p>
<h2>綠色標題</h2>
</body>
分離結構與表現,利於緩存、維護、團隊協作。
<!-- HTML -->
<head>
<link rel="stylesheet" href="styles/main.css">
</head>
<!-- main.css -->
:root {
--primary-color: #007bff;
--text-base: #212529;
}
body { color: var(--text-base); }
.btn-primary { color: white; background: var(--primary-color); }
| 格式 | 語法 | 示例 |
|---|---|---|
| 關鍵字 | red | color: red; |
| 十六進制 | #RRGGBB / #RGB | #ff0000 / #f00 |
| RGB | rgb(255,0,0) | color: rgb(255, 0, 0); |
| RGBA | rgba(255,0,0,0.5) | 帶透明度 |
| HSL | hsl(0, 100%, 50%) | 色相/飽和度/亮度 |
| HSLA | hsla(0, 100%, 50%, 0.5) | 帶透明度 |
prefers-color-scheme 實現深色模式自適應。