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

CSS Setting Link Color: Đặt màu cho liên kết

CSS cho phép chúng ta tô màu cho các liên kết (links). Thuộc tính color được dùng để thiết lập màu văn bản cho một phần tử.

Thứ tự pseudo-selector: :link, :visited, :hover, :active (nhớ: LoVe HeArt).

Cú pháp

selector {
    color: /* value */;
}

Ví dụ 1: Màu cho 4 trạng thái link

<!DOCTYPE html>
<html>
<head>
<style>
#demo::after {
    content: " (visited)";
    font-style: italic;
}
a:link { color: lime; }
a:visited { color: green; }
a:hover { color: orange; }
a:active { color: gold; }
</style>
</head>
<body>
<h2>Demo Links</h2>
<a id="demo" href="">This is demo text 1.</a>
<hr>
<p><a href="#">This is demo text 2.</a></p>
</body>
</html>

Kết quả: Link 1 (href rỗng) được coi là visited → màu green + "(visited)". Link 2: hover → orange, active (click) → gold.

Ví dụ 2: Link trong div

<!DOCTYPE html>
<html>
<head>
<style>
div {
    margin: auto; font-size: 1.4em;
    background-color: lightseagreen;
    width: 100px; text-align: center;
}
a:link { color: rebeccapurple; }
</style>
</head>
<body>
<div>
    <a id="demo" href="">Demo link.</a>
</div>
</body>
</html>

Default Link Colors (Có thể thay đổi theo trình duyệt)

Trạng tháiMàu mặc định
Link (chưa visit)#0000EE (xanh dương)
Visited#551A8B (tím)
Hover#0000EE (xanh dương)
Active#EE0000 (đỏ)
FocusOutline xanh/da cam tùy OS

Best Practice: CSS Custom Properties cho Link System

:root {
    --link-color: #0066cc;
    --link-hover: #004499;
    --link-visited: #663399;
    --link-active: #cc0000;
    --link-focus: #0066cc;
}

a { color: var(--link-color); text-decoration: none; }
a:hover { color: var(--link-hover); text-decoration: underline; }
a:visited { color: var(--link-visited); }
a:active { color: var(--link-active); }
a:focus-visible { outline: 2px solid var(--link-focus); outline-offset: 2px; }

Lưu ý Privacy: :visited

Vì lý do bảo mật, trình duyệt hạn chế các style có thể áp dụng cho :visited:

  • Chỉ cho phép: color, background-color, border-color, column-rule-color, outline-color, text-decoration-color, text-emphasis-color
  • getComputedStyle trên link visited luôn trả về giá trị unvisited
  • Không thể dùng :visited selector trong querySelector để detect history