Pseudo-element ::selection cho phép tùy chỉnh màu nền và màu chữ khi người dùng bôi đen (select) văn bản.
Ví dụ mã nguồn
<!DOCTYPE html>
<html>
<head>
<style>
::-moz-selection { /* Firefox cũ */
color: rgb(255, 255, 255);
background: rgb(118, 69, 231);
}
::selection { /* Chuẩn hiện đại: Chrome, Safari, Firefox 62+, Edge */
color: rgb(255, 255, 255);
background: rgb(118, 69, 231);
}
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
p { font-size: 40px; line-height: 1.6; }
</style>
</head>
<body>
<h1>Text Selection Color Example</h1>
<h2>Thử bôi đen văn bản dưới đây</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto consequuntur fugiat doloremque adipisci vero iste soluta ea ut! Exercitationem rem dolore delectus modi repellat quo mollitia temporibus laudantium, alias itaque tempora, iure voluptatem non voluptas, deleniti laborum? Cum ducimus unde, vitae consequuntur nobis dignissimos similique officia possimus quis necessitatibus praesentium!</p>
</body>
</html>
Các thuộc tính được hỗ trợ trong ::selection
color- Màu chữbackground-color/background- Màu nềntext-shadow- Đổ bóng chữtext-decoration- Gạch chân, gạch ngang- KHÔNG hỗ trợ: font-size, font-family, margin, padding, border, opacity, transform...
Áp dụng cho element cụ thể
/* Chỉ đổi selection cho paragraph */
p::selection { background: yellow; color: black; }
/* Chỉ cho code block */
code::selection { background: #2d2d2d; color: #f8f8f2; }
/* Input/textarea */
input::selection, textarea::selection { background: #007bff; color: white; }
Hỗ trợ trình duyệt
- Chrome 1+, Safari 1.1+, Firefox 62+ (cần
::-moz-selectioncho cũ), Edge 12+, Opera 9.5+ - IE: Không hỗ trợ (IE 11 không hỗ trợ ::selection)
Ứng dụng
- Branding: Màu selection theo brand color
- Code blocks: Selection tối màu cho code
- Accessibility: Đảm bảo contrast ratio ≥ 4.5:1 giữa text và background selection
- Print:
::selectionkhông ảnh hưởng in ấn