| 方式 | 語法 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|---|
| 外部樣式表 | <link rel="stylesheet" href="path.css"> | 多頁面共用樣式、站點級主題 | 結構分離、瀏覽器快取、維護容易、團隊協作 | 額外 HTTP 請求、首屏載入稍慢 |
| 內部樣式表 | <style>...</style> 在 <head> | 單頁面專用樣式、動態樣式、Email 模板 | 無額外請求、頁面獨立、可用 JSP 變數動態生成 | 無法快取、重複代碼、污染全域命名空間 |
| 內聯樣式 | <div style="color:red;"> | 極少數一次性覆蓋、HTML Email、動態計算樣式 | 優先級最高、無選擇器匹配開銷 | 結構表現混淆、不可複用、維護噩夢、CSP 政策限制 |
<%@ page contentType="text/html;charset=UTF-8" %>
<%
String ctx = request.getContextPath();
String version = "v20240115"; // 版本號防快取
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=ctx%>/">
<link rel="stylesheet" href="css/common.css?<%=version%>">
<link rel="stylesheet" href="css/page.css?<%=version%>">
<!-- 條件載入 IE 專用樣式 -->
<!--[if IE]><link rel="stylesheet" href="css/ie.css"><![endif]-->
</head>
技巧: 使用 <base> 標籤或 EL ${pageContext.request.contextPath} 構建絕對路徑,加上版本查詢字串防快取。
<%@ page import="com.example.config.ThemeConfig" %>
<%
ThemeConfig theme = ThemeConfig.getCurrent();
%>
<head>
<style>
:root {
--primary-color: <%=theme.getPrimaryColor()%>;
--font-size: <%=theme.getFontSize()%>px;
}
.btn-primary { background: var(--primary-color); }
.dynamic-text { font-size: var(--font-size); }
</style>
</head>
適用於:用戶自訂主題、A/B 測試樣式、後台動態配置色系。
<div style="width: <%=colWidth%>px; background: <%=bgColor%>;">內容</div>
<!-- JSTL/EL 版本 -->
<div style="width: ${colWidth}px; background: ${bgColor};">內容</div>
僅用於:動態計算的寬高、顏色等**極少數**屬性。大部分樣式應定義在 CSS 類別中。
優先級權重計算:(內聯, ID, 類/屬性/偽類, 元素/偽元素)
!important > 內聯(1,0,0,0) > ID(0,1,0,0) > 類/屬性/偽類(0,0,1,0) > 元素/偽元素(0,0,0,1) > 通配符(0,0,0,0) > 繼承 > 瀏覽器預設
<style>
/* 權重 0,0,1,0 */
.box { color: blue; }
/* 權重 0,1,0,0 */
#special { color: red; }
</style>
<div id="special" class="box" style="color: green;">文字</div>
<!-- 結果:綠色 (內聯 1,0,0,0 勝出) -->
<%-- 使用 Maven 資源過濾注入版本號 --%>
<link href="css/main.css?v=@project.version@" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.min.js"></script>
<link rel="stylesheet" href="css/ie8-fix.css">
<![endif]-->
<!-- 開發環境:多檔案 -->
<c:if test="${devMode}">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/layout.css">
<link rel="stylesheet" href="css/component.css">
</c:if>
<!-- 生產環境:合併壓縮 -->
<c:if test="${not devMode}">
<link rel="stylesheet" href="css/bundle.min.css">
</c:if>
<!-- 禁止內聯樣式,需 nonce 或 hash --%>
<meta http-equiv="Content-Security-Policy"
content="style-src 'self' 'nonce-{{randomNonce}}';">
<style nonce="<%=nonce%>">...</style>
<style> 定義 :root { --var: value; },元素套用 var(--var)style="--width: ${val}px;" + CSS width: var(--width)Cache-Control: max-age=31536000 + 檔名含雜湊值JSP 引入 CSS 三種方式各有定位:**外部樣式表為主流標準**,內部樣式表處理動態主題,內聯樣式極少數例外。理解優先級計算規則,善用 CSS 變數替代內聯樣式,配合建構工具最佳化載入效能,是現代 JSP 前端工程化的關鍵。