CSS Universal Selector (*) ใช้ target ทุก elements บนหน้าเว็บ
Universal selector syntax:
* { property-name: value; }
ตัวอย่าง การใช้ universal selector เพื่อกำหนด box-sizing ให้ทุก elements:
*, *:before, *:after {
box-sizing: border-box;
}
โค้ดด้านบนใช้ universal selector * ร่วมกับ pseudo-elements :before และ :after เพื่อ apply border-box ให้ทุก elements รวมถึง pseudo-elements
Universal selector มี specificity ต่ำสุด (0,0,0) หมายความว่า styles ที่ประกาศด้วย universal selector จะถูก override ได้ง่ายโดย selector ใดๆ ที่มี specificity สูงกว่า
Use Cases (กรณีการใช้งาน)
1. Reset / Normalize Styles
ใช้ universal selector เพื่อ reset หรือ normalize default browser styles:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
2. Global Typography Settings
ตั้งค่า typography พื้นฐานให้ทั้งหน้า:
* {
font-family: inherit;
line-height: 1.5;
}
3. Debugging Layout Issues
ใช้ช่วงเวลาสั้นๆ เพื่อ visualize element boundaries:
* {
outline: 1px solid red;
}
คำเตือน (Caveats)
- Performance: Universal selector อาจส่งผลต่อ performance หากใช้กับ rules ที่ซับซ้อนหรือบนหน้าที่มี elements มากมาย เนื่องจาก browser ต้อง evaluate rule นี้กับทุก element
- Specificity: Specificity ต่ำมาก อาจทำให้ยากที่จะ override styles หากไม่ระมัดระวัง
- Inheritance: บาง properties ไม่ inherit (เช่น margin, padding, border) การใช้ universal selector สำหรับ properties เหล่านี้อาจให้ผลลัพธ์ที่ไม่คาดคิด
Best Practices
- ใช้ universal selector เฉพาะสำหรับ global reset/normalize และ box-sizing
- หลีกเลี่ยงการใช้ universal selector สำหรับ layout properties (margin, padding, width, height)
- พิจารณาใช้
:rootหรือhtmlselector สำหรับ global CSS custom properties (variables) แทน