Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การตั้งค่าสีข้อความขององค์ประกอบด้วย CSS

คุณสมบัติ 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>

ผลลัพธ์

การตั้งค่าสีข้อความขององค์ประกอบด้วย CSS

ตัวอย่างที่ 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>

ผลลัพธ์

การตั้งค่าสีข้อความขององค์ประกอบด้วย CSS

รูปแบบค่าสี (Color Formats) - สรุป

FormatSyntaxRangeAlpha
Namedred140+ namesไม่มี
Hex 3/6/8 digits#f00, #ff0000, #ff0000ff0-F8 digits
RGB/RGBArgb(255,0,0), rgba(255,0,0,0.5)0-255 / 0-100%0-1 / 0-100%
HSL/HSLAhsl(0,100%,50%), hsla(0,100%,50%,0.5)H:0-360, S/L:0-100%0-1 / 0-100%
HWBhwb(0 0% 0%)H:0-360, W/B:0-100%ไม่มี (แยก)
LCHlch(50% 100 40)L:0-100%, C:0-230, H:0-360ไม่มี
LABlab(50% 100 0)L:0-100%, a:-125-125, b:-125-125ไม่มี
color()color(display-p3 1 0 0)ขึ้นกับ color spaceoptional

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 ตรวจสอบ