คุณสมบัติ color ใน CSS ใช้เปลี่ยนสีข้อความขององค์ประกอบ สามารถระบุค่าเป็นชื่อสีมาตรฐาน, rgb(), rgba(), hsl(), hsla() และค่า hexadecimal
ไวยากรณ์ (Syntax)
Selector {
color: /*value*/;
}
ตัวอย่างที่ 1: ใช้ RGBA, HSL, Hex
<!DOCTYPE html>
<html>
<head>
<style>
div { height: 50px; width: 50px; float: right; color: white; background-color: #2f5587; }
p { color: rgba(225,5,135,0.7); border: 2px solid #16c618; box-shadow: 0 7px 0 5px hsl(90, 60%, 70%); }
</style>
</head>
<body>
<h2>Example Heading</h2>
<div>This is it</div>
<p>Demo text is visible here.</p>
</body>
</html>
ผลลัพธ์

ตัวอย่างที่ 2: ใช้ nth-of-type(even) กำหนดสีสลับ
<!DOCTYPE html>
<html>
<head>
<style>
li:nth-of-type(even) {
color: dodgerblue; border: 6px groove #16c618;
padding: 4px; box-shadow: inset -100px 0 5px red;
}
</style>
</head>
<body>
<h2>Learn Servlets</h2>
<ul>
<li>Java Servlets are programs that run on a Web or Application server.</li>
<li>Java Servlets often serve the same purpose as programs implemented using the CGI.</li>
<li>Servlets are platform-independent because they are written in Java. </li>
</ul>
</body>
</html>
ผลลัพธ์

รูปแบบค่าสี (Color Formats) - สรุป
| Format | Syntax | Range | Alpha |
|---|---|---|---|
| Named | red | 140+ names | ไม่มี |
| Hex 3/6/8 digits | #f00, #ff0000, #ff0000ff | 0-F | 8 digits |
| RGB/RGBA | rgb(255,0,0), rgba(255,0,0,0.5) | 0-255 / 0-100% | 0-1 / 0-100% |
| HSL/HSLA | hsl(0,100%,50%), hsla(0,100%,50%,0.5) | H:0-360, S/L:0-100% | 0-1 / 0-100% |
| HWB | hwb(0 0% 0%) | H:0-360, W/B:0-100% | ไม่มี (แยก) |
| LCH | lch(50% 100 40) | L:0-100%, C:0-230, H:0-360 | ไม่มี |
| LAB | lab(50% 100 0) | L:0-100%, a:-125-125, b:-125-125 | ไม่มี |
| color() | color(display-p3 1 0 0) | ขึ้นกับ color space | optional |
Accessibility: Color Contrast
- WCAG AA: Contrast ratio ≥ 4.5:1 (normal text), ≥ 3:1 (large text 18px+ หรือ bold 14px+)
- WCAG AAA: ≥ 7:1 (normal), ≥ 4.5:1 (large)
- ใช้เครื่องมือเช่น WebAIM Contrast Checker ตรวจสอบ