CSS Grouping Selector ใช้เลือกหลายองค์ประกอบและจัดสไตล์ร่วมกัน ลดโค้ดซ้ำและความพยายามในการประกาศสไตล์ร่วมสำหรับแต่ละองค์ประกอบ แยกตัวเลือกแต่ละตัวด้วยจุลภาค (comma)
ไวยากรณ์ (Syntax)
element, element {
/* declarations */
}
ตัวอย่างที่ 1: จัดกลุ่ม article, p, img
<!DOCTYPE html>
<html>
<head>
<style>
article, p, img {
display: block; margin: auto; text-align: center; border-bottom: double orange;
}
</style>
</head>
<body>
<article>Demo Text</article>
<p>This is demo text.</p>
<br/>
<img src="https://www.tutorialspoint.com/swing/images/swing.jpg">
</body>
</html>
ผลลัพธ์

ตัวอย่างที่ 2: จัดกลุ่ม Pseudo-elements
<!DOCTYPE html>
<html>
<head>
<style>
div::after, p::after {
content: "Demo text"; margin: 4px; box-shadow: inset 0 0 4px darkorange;
}
</style>
</head>
<body>
<div></div>
<p>This is example text.</p>
</body>
</html>
ผลลัพธ์

ประโยชน์ของ Grouping Selectors
- DRY (Don't Repeat Yourself): เขียนสไตล์ร่วมครั้งเดียว
- Maintainability: แก้ไขที่เดียว ครอบคลุมทุกตัวเลือก
- File size: ลดขนาด CSS file
- Consistency: รับประกันสไตล์สอดคล้องกัน
ข้อควรระวัง
- หาก ตัวเลือกใดตัวเลือกหนึ่ง invalid ทั้งกลุ่มจะถูกละเว้น (selector list forgiveness ไม่มีใน CSS)
- Specificity คำนวณจาก ตัวเลือกที่เฉพาะเจาะจงที่สุด ในกลุ่ม
- ไม่ควรจัดกลุ่มเยอะเกินไป ทำให้ยากต่อการ debug
ตัวอย่าง Invalid Selector ในกลุ่ม
/* ❌ ผิด: :invalid-pseudo ไม่มีอยู่จริง ทั้งกลุ่ม fail */
h1, h2, :invalid-pseudo { color: red; }
/* ✅ ถูก: แยกออกมา */
h1, h2 { color: red; }
/* :invalid-pseudo { ... } แยกหรือลบ */
Modern: :is() และ :where()
/* :is() - specificity = ตัวเลือกที่สูงสุดในกลุ่ม */
:is(h1, h2, h3) { color: red; } /* specificity = h1 (0,0,1) */
/* :where() - specificity = 0 เสมอ */
:where(h1, h2, h3) { color: red; } /* specificity = 0,0,0 ง่ายต่อการ override */