Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

CSS text-decoration: Trang trí văn bản

Thuộc tính CSS text-decoration được dùng để áp dụng trang trí cho văn bản của phần tử được chọn. Có thể thêm line-through, overline, underline, v.v. Đây là shorthand cho text-decoration-line, text-decoration-color và text-decoration-style.

Cú pháp

selector {
    text-decoration: /* line || style || color */;
}

/* Hoặc tách riêng */
selector {
    text-decoration-line: underline | overline | line-through | blink;
    text-decoration-style: solid | double | dotted | dashed | wavy;
    text-decoration-color: /* color */;
    text-decoration-thickness: auto | /* length */;
    text-underline-offset: /* length */;
}

Ví dụ 1: Overline với ::before

<!DOCTYPE html>
<html>
<head>
<style>
p:nth-child(2)::before {
    content: " We will reach the destination ";
    background-color: lightgreen;
    text-decoration: overline blue;
    font-size: 1.2em;
}
</style>
</head>
<body>
<p>I'm not the only traveller</p>
<p> before night. </p>
</body>
</html>

Ví dụ 2: Line-through và underline

<!DOCTYPE html>
<html>
<head>
<style>
span {
    background: rgb(204,22,50);
    text-decoration: blue line-through;
    font-style: italic; color: white;
}
p { text-decoration: underline; }
</style>
</head>
<body>
<h2>Department Details</h2>
<p>
The employees of Department Marketing, Operations, Finance,
<span>IT</span> are requested to email their original documents.
<span> Delay in submission will lead to delayed verification.</span>
</p>
</body>
</html>

Các giá trị text-decoration-line

Giá trịHiển thịDùng cho
underlineGạch chânLink, emphasis
overlineGạch trênĐặc biệt, heading
line-throughGạch ngangĐã xóa, giá cũ, completed task
blinkNhấp nháy (deprecated)Không khuyến khích

text-decoration-style

  • solid (mặc định)
  • double
  • dotted
  • dashed
  • wavy — rất đẹp cho link hover, error underline

Kết hợp nhiều dòng (Multiple decorations)

.special {
    text-decoration: underline overline line-through;
    text-decoration-color: red blue green;
    text-decoration-style: solid wavy dotted;
}

Ứng dụng thực tế

/ * Giá cũ - gạch ngang đỏ */
.old-price {
    text-decoration: line-through red;
    text-decoration-thickness: 2px;
}

/ * Link hover - gạch chân sóng */
a:hover {
    text-decoration: underline wavy currentColor;
    text-underline-offset: 4px;
}

/ * Hoàn thành task */
.task-done {
    text-decoration: line-through;
    opacity: 0.6;
}

/ * Đánh dấu lỗi chính tả */
.spelling-error {
    text-decoration: underline wavy red;
    text-decoration-thickness: 2px;
}