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

เปลี่ยนสี Bullet Points ใน List ด้วย CSS ::marker Selector

CSS ::marker Pseudo-element ใช้จัดสไตล์ Bullet Points (หรือตัวเลขใน Ordered List) โดยตรง ไม่ต้องใช้ list-style-image หรือ Hack ด้วย ::before แล้ว

Syntax

selector::marker {
  property: value;
}

Properties ที่รองรับ

Propertyคำอธิบาย
colorสีของ Marker (Bullet/Number)
font-sizeขนาด Marker
font-weightความหนาของ Marker
contentเปลี่ยนเนื้อหา Marker (Custom Bullet)
white-spaceควบคุม whitespace

ตัวอย่างที่ 1: เปลี่ยนสี Bullet ให้เป็นสีเขียว

<!DOCTYPE html>
<html>
<head>
  <style>
    ul {
      list-style: circle;
      font-size: 1.2em;
    }
    li::marker {
      color: green;
    }
  </style>
</head>
<body>
  <h2><strong>TMNT</strong></h2>
  <ul>
    <li>Raphael</li>
    <li>Donatello</li>
    <li>Michaelangelo</li>
    <li>Leonardo</li>
  </ul>
</body>
</html>

ตัวอย่างที่ 2: Square Bullets + Float Layout

<!DOCTYPE html>
<html>
<head>
  <style>
    ul {
      list-style: square;
      overflow: hidden;
    }
    li::marker { color: green; }
    li {
      width: 15%;
      margin: 2%;
      float: left;
      box-shadow: inset 2px 0px 10px lightblue;
    }
  </style>
</head>
<body>
  <ul>
    <li>ting</li>
    <li>tong</li>
    <li>ding</li>
    <li>dong</li>
  </ul>
</body>
</html>

Advanced ::marker Techniques

1. Custom Bullet Characters

li::marker {
  content: "→ "; /* หรือ ▸ ► ◆ ◇ ✦ ✧ ★ ☆ ♥ ♦ ♣ ♠ */
  color: #e91e63;
  font-size: 1.2em;
}

2. Emoji Bullets

li::marker {
  content: "🎯 "; /* 🎨 🎭 🎪 🎨 🎯 🎲 🎮 🎰 */
  font-size: 1.1em;
}

3. Counter-based Numbering (Ordered List)

ol {
  list-style: none;
  counter-reset: my-counter;
}
li::marker {
  content: counter(my-counter) ".";
  counter-increment: my-counter;
  color: #673ab7;
  font-weight: bold;
}

4. Styling ตาม Index (nth-child)

li:nth-child(odd)::marker { color: #2196f3; }
li:nth-child(even)::marker { color: #f44336; }
li:nth-child(3n)::marker { content: "★ "; color: #ffc107; }

5. Marker เฉพาะ List ที่มี Class

.task-list li::marker {
  content: "☐ ";
  color: #4caf50;
}
.task-list li.done::marker {
  content: "✓ ";
  color: #4caf50;
}

Browser Support

  • Chrome 86+, Firefox 68+, Safari 11.1+, Edge 86+
  • IE: ไม่รองรับ (ใช้ Fallback ด้วย ::before)
  • content property ใน ::marker รองรับใน Firefox 71+, Chrome 86+, Safari 15+

Fallback สำหรับ Browser เก่า

/* Modern */
li::marker { color: red; }

/* Fallback (IE11, Old Browsers) */
li {
  list-style: none;
}
li::before {
  content: "• ";
  color: red;
  display: inline-block;
  width: 1em;
  margin-left: -1em;
}

Best Practices

  • ใช้ ::marker แทน ::before เพื่อ Semantic และ Performance
  • จับคู่สี Marker กับ Brand Color หรือ Text Color
  • ขนาด Marker ควรสัมพันธ์กับ Font-size ของ List Item
  • Custom Bullet ควรใช้ Unicode Characters ที่รองรับกว้าง (ไม่ใช่ Emoji ทั้งหมด)