JSP 頁面引用外部 CSS 文件,兩個按鈕分別應用 .button_blue 和 .button_green 類。運行時「登錄」按鈕樣式正常,「註冊」按鈕樣式失效。但將樣式內聯到頁面 <style> 標簽中則生效。
.button_green,且由於加載順序在後,其優先級相同時「後來者居上」生效。<head> 內聯後,因內聯樣式優先級高於外部文件,故生效。.button_green 樣式來源,被劃線的即為被覆蓋的聲明。確保自定義 CSS 文件在 最後引用,這樣其同名類聲明優先級最高。
<link rel="stylesheet" href="common.css" />
<link rel="stylesheet" href="third-party.css" />
<link rel="stylesheet" href="custom.css" /> <!-- 最後加載 -->
/* 增加父級類名提高權重 */
.my-form .button_green { ... }
.button_green {
background: #aef055 !important;
/* 其他屬性同理 */
}
注意:濫用 !important 會破壞樣式層級結構,僅在無法調整順序或具體性時使用。
.btn--green 而非 .button_green)。