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

Advanced Selectors ใน CSS

Advanced CSS Selectors: เลือก Element ได้ละเอียดและยืดหยุ่น

รวม Combinators, Attribute selectors, Pseudo-classes, Pseudo-elements ที่ทรงพลังกว่า class/id selectors ธรรมดา

Combinators

Selectorชื่อคำอธิบาย
A BDescendantB ภายใน A (ทุกระดับ)
A > BDirect ChildB เป็นลูกโดยตรงของ A
A + BAdjacent SiblingB ติด A ทันที (same parent)
A ~ BGeneral SiblingB อยู่หลัง A (same parent, ไม่จำเป็นติด)

Advanced Selectors ในตัวอย่าง

<style>
  #red { color: red; }                    /* ID selector */
  .green { background: green; }           /* Class selector */
  ul:nth-of-type(1) { background: rgb(0, 174, 255); } /* Structural pseudo */
  ul + h3 { border: 4px solid rgb(19, 0, 128); }     /* Adjacent sibling */
  a[href="https://www.wikipedia.org"] { font-size: 25px; } /* Attribute */
  h1 ~ h3 { font-size: 40px; }            /* General sibling */
  div > span { background-color: DodgerBlue; }        /* Direct child */
</style>

Modern Selectors (CSS4 / Selectors Level 4)

  • :is() – :is(h1, h2, h3) { color: red; } กลุ่ม selector specificity = สูงสุดในกลุ่ม
  • :where() – :where(h1, h2, h3) { color: red; } specificity = 0 (ต่ำสุด)
  • :has() – div:has(> img) { ... } Parent selector! รองรับ Chrome 105+, FF 121+, Safari 15.4+
  • :not() enhanced – :not(.a, .b, .c) หลาย arguments
  • ::marker – style list marker (bullet/number)
  • ::file-selector-button – style input[type=file] button

Specificity Quick Reference

  • Inline style: (1,0,0,0)
  • ID: (0,1,0,0)
  • Class/Attribute/Pseudo-class: (0,0,1,0)
  • Element/Pseudo-element: (0,0,0,1)
  • :where(): (0,0,0,0)

Best Practices

  • หลีกเลี่ยง ID selectors สำหรับ styling (specificity สูงเกิน)
  • ใช้ class เพื่อความเป็น modular/reusable
  • ใช้ :where() สำหรับ reset/normalize styles
  • ใช้ :is() กลุ่ม selectors ลดโค้ดซ้ำ
  • :has() เปิดโอกาส component-based styling ที่เคยต้องใช้ JS