CSS 文字裝飾 (text-decoration)
text-decoration 用來設定文字的裝飾線,例如底線、刪除線等。
text-decoration-line(裝飾線位置)
設定裝飾線出現的位置。
.underline {
text-decoration-line: underline; /* 底線 */
}
.overline {
text-decoration-line: overline; /* 頂線 */
}
.line-through {
text-decoration-line: line-through; /* 刪除線 */
}
.none {
text-decoration-line: none; /* 無裝飾線 */
}
/* 可以組合多種 */
.multiple {
text-decoration-line: underline overline;
}
text-decoration-color(裝飾線顏色)
設定裝飾線的顏色。
a {
text-decoration-line: underline;
text-decoration-color: red;
}
text-decoration-style(裝飾線樣式)
設定裝飾線的樣式。
.solid {
text-decoration-style: solid; /* 實線(預設) */
}
.double {
text-decoration-style: double; /* 雙線 */
}
.dotted {
text-decoration-style: dotted; /* 點線 */
}
.dashed {
text-decoration-style: dashed; /* 虛線 */
}
.wavy {
text-decoration-style: wavy; /* 波浪線 */
}
text-decoration-thickness(裝飾線粗細)
設定裝飾線的粗細。
a {
text-decoration-line: underline;
text-decoration-thickness: 2px;
}
.thick {
text-decoration-thickness: 0.2em;
}
.auto {
text-decoration-thickness: auto; /* 自動(預設) */
}
.from-font {
text-decoration-thickness: from-font; /* 使用字型定義的粗細 */
}
text-decoration(縮寫屬性)
text-decoration 是一個縮寫屬性,可以一次設定多個裝飾相關屬性。
a {
text-decoration: underline red wavy 2px;
}
/* 等同於 */
a {
text-decoration-line: underline;
text-decoration-color: red;
text-decoration-style: wavy;
text-decoration-thickness: 2px;
}
text-underline-offset(底線偏移)
設定底線和文字之間的距離。
a {
text-decoration: underline;
text-underline-offset: 4px; /* 底線往下移 4px */
}
.negative {
text-underline-offset: -2px; /* 底線往上移 */
}
實用範例
移除連結底線
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
自訂底線樣式
a {
text-decoration: underline;
text-decoration-color: rgba(0, 0, 255, 0.3);
text-decoration-thickness: 2px;
text-underline-offset: 3px;
}
a:hover {
text-decoration-color: blue;
}
刪除線效果
.sold-out {
text-decoration: line-through;
text-decoration-color: red;
color: gray;
}
.discount {
text-decoration: line-through;
text-decoration-thickness: 2px;
}
強調標記
.important {
text-decoration: underline wavy red;
}
.highlight {
text-decoration: underline dotted;
text-decoration-color: orange;
text-underline-offset: 2px;
}
瀏覽器支援注意事項
較新的屬性如 text-decoration-thickness 和 text-underline-offset 在舊版瀏覽器可能不支援。如需更好的相容性,可以考慮使用 border-bottom 或偽元素來製作底線效果:
/* 使用 border-bottom 替代 */
a {
text-decoration: none;
border-bottom: 2px solid blue;
padding-bottom: 2px;
}