เรียนรู้ select ทุก HTML elements ยกเว้นตัวแรก ด้วย CSS `:not(:first-child) selector
เพิ่ม rule-set นี้ใน CSS stylesheet ทุก h2 element บนเว็บจะได้ 64px top margin
h2 { margin-top: 64px; }
แต่ไม่อยากให้ top margin ตัว h2 แรกบนเว็บ แตะทุกตัวอื่น?
ใช้ :not(:first-child) selector
เพิ่ม rule-set นี้ใน stylesheet:
h2:not(:first-child) { margin-top: 64px; }
ตอนนี้ทุก h2 element บนเว็บได้ margin-top เดียวกัน — ยกเว้น h2 แรกบนแต่ละ document (page/post)
Use Case สำหรับ :not(:first-child) selector
สมมติ styling typographic layout เว็บ ตัดสินใจ article h2 heading elements ควรมี margin-top: 64px; ให้ breathing room ระหว่าง sections
แตะ top ของทุก article มี intro section magazine/poster style พร้อม cover image, overlay, text elements บนภาพ อาจใช้ heading elements หลายตัว (h1 title, h2 tagline ฯลฯ)
ในกรณีนี้ ไม่อยากใช้ spacing values (margin/padding) เดียวกับใน article ด้วย :not(:first-child) selector แก้ปัญหานี้ได้
ใช้ selector นี้ได้ทุก HTML element อีก use case เหมือนกัน: unordered list <ul> สำหรับ menu อาจมี styling เฉพาะสำหรับ ul ใน menu แตะไม่ใช่เว็บอื่นๆ (alignment, borders, colors)
CSS ไม่ได้แค่ styling ด้วย classes ไหม?
Modern web development นิยมหลีกเลี่ยง styling element selectors โดยตรง ใช้ classes แทน ผมชอบ classes เพราะทำให้ CSS scalable/reusable บน web platforms ที่โต
แต่ direct selector styling ยังมีที่ establis baseline/global styling โดยตรงบน element selectors ให้ consistency/uniformity ผ่าน product UI อัตโนมัติ ช่วยประหยัด repetitive UI styling — ถ้าทำถูกต้อง