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

วิธีเปลี่ยนสีค่_DEFAULT ของการเลือกข้อความ (Text Selection) ด้วย CSS

::selection Pseudo-element: จัดสไตล์ข้อความที่ถูก Highlight

ใช้ ::selection (standard) และ ::-moz-selection (Firefox legacy) เปลี่ยนสีพื้นหลังและสีข้อความเมื่อผู้ใช้เลือก (highlight) ข้อความ

โค้ดตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    ::-moz-selection { color: rgb(255, 255, 255); background: rgb(118, 69, 231); }
    ::selection { color: rgb(255, 255, 255); background: rgb(118, 69, 231); }
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    p { font-size: 40px; }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Text Selection Color</h1>
  <h2>ลอง Select ข้อความด้านล่างดู</h2>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit...</p>
</body>
</html>

Property ที่รองรับใน ::selection

  • color – สีข้อความ
  • background-color / background – สีพื้นหลัง
  • text-shadow – เงาข้อความ
  • ไม่รองรับ: font-size, font-family, border, padding, margin, etc.

Scoped Selection Style

.highlight-area::selection { background: yellow; color: black; }
.code-block::selection { background: #444; color: #0f0; }

Browser Support

  • ::selection – ทุก browser สมัยใหม่
  • ::-moz-selection – Firefox เก่า (ยังต้องใส่ไว้เผื่อ)
  • IE 9+ รองรับ ::selection

Use Cases

  • Branding: ใช้ brand color เป็น selection background
  • Code blocks: สีพื้นหลังมืด สีข้อความสว่าง – อ่านโค้ดที่ highlight ง่าย
  • Print stylesheet: ::selection { background: none; } ป้องกันพิมพ์สี