Thuộc tính CSS color được dùng để thiết lập màu văn bản cho một phần tử.
Cú pháp
selector {
color: /* giá trị màu */;
}
Các định dạng màu
| Định dạng | Ví dụ | Mô tả |
|---|---|---|
| Tên màu | red, rebeccapurple | 140+ tên màu chuẩn |
| Hex | #ff0000, #f00 | 6 hoặc 3 ký tự hex |
| RGB | rgb(255,0,0) | 0-255 mỗi kênh |
| RGBA | rgba(255,0,0,0.5) | Có alpha (độ trong suốt) |
| HSL | hsl(0,100%,50%) | Hue(0-360), Saturation, Lightness |
| HSLA | hsla(0,100%,50%,0.5) | HSL + alpha |
| Modern | rgb(255 0 0 / 0.5) | Cú pháp mới (CSS Color 4) |
Ví dụ 1: Màu cho div lồng nhau
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
height: 100px; width: 200px;
margin: 10px; display: flex; float: left;
font-size: 1.4em; word-spacing: 30px;
line-height: 4.5em; border: thin solid blue;
border-radius: 40%; text-align: center;
color: rebeccapurple;
}
div + div {
background-color: beige;
color: red;
text-align: justify;
text-decoration: line-through;
}
</style>
</head>
<body>
<div>One Two</div>
<div>Three</div>
</body>
</html>
Ví dụ 2: Màu cho text và span bên trong
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p {
margin: 10px; display: flex; float: left;
border: 3px groove green; text-align: center;
color: rebeccapurple;
}
span {
background-color: beige;
color: red;
text-decoration: underline;
}
</style>
</head>
</head>
<body>
<h2>What is Tableau?</h2>
<p>Tableau is a Business Intelligence tool for visually analyzing the data.
<span>Users can create and distribute an interactive and shareable dashboard...</span>
Tableau can connect to files, relational and Big Data sources...</p>
</body>
</html>
Kế thừa (Inheritance)
color được kế thừa từ phần tử cha. Thiết lập trên body sẽ áp dụng cho toàn trang:
body {
color: #333; /* Màu văn bản mặc định cho toàn site */
font-family: system-ui, sans-serif;
}
CurrentColor
currentColor là keyword đại diện cho giá trị color tính toán được của phần tử, hữu ích cho border, box-shadow, SVG:
.icon {
width: 24px; height: 24px;
fill: currentColor; /* SVG icon kế thừa màu text */
}
.button {
color: #0066cc;
border: 2px solid currentColor;
}
.button:hover { color: #004499; } /* Border tự đổi theo */
Accessibility: Contrast Ratio
Đảm bảo tỷ lệ đối比 (contrast) đủ lớn giữa text và background (WCAG AA: 4.5:1 cho text thường, 3:1 cho text lớn).