CSS Child Selector (>) ใช้เลือก element ที่เป็น **ลูกโดยตรง (direct children)** ของ parent element เท่านั้น ไม่รวมหลาน (grandchildren) หรือระดับลึกกว่า
Syntax
parent > child { /* declarations */ }
ตัวอย่างที่ 1: Article > Div > P
<!DOCTYPE html> <html> <head> <style> * { padding: 5px; } article > div { border: dashed midnightblue; width: 45%; } div > p { font-size: 20px; font-style: italic; box-shadow: inset 0 0 8px orange; } </style> </head> <body> <h2>Examination Detail</h2> <article> <div>Exam Details</div> <div><p>Exam begins at 11AM.</p></div> <span><div> Do not bring cell phone.</div></span> <div> <div>Candidates should reach the center till 10:45.</div> <br/> The candidates need to be bring the Admit Card. </div> </article> </body> </html>
ตัวอย่างที่ 2: Nested Divs
<!DOCTYPE html> <html> <head> <style> div { margin: auto; width: 200px; padding: 30px; background-color: moccasin; } div > div { box-shadow: inset 0 0 8px mediumseagreen; border-top-right-radius: 50%; border-bottom-left-radius: 50%; } </style> </head> <body> <div> <div></div> </div> </body> </html>
คำอธิบาย
ตัวอย่างที่ 1:
article > div- เลือก div 3 ตัวที่เป็นลูกโดยตรงของ article (ไม่รวม div ใน span และ div ใน div)div > p- เลือก p ที่เป็นลูกโดยตรงของ div (เฉพาะใน div ที่ 2 เท่านั้น)
ตัวอย่างที่ 2: div > div เลือก div ภายใน div ระดับ 1 เท่านั้น
Child Selector vs Descendant Selector:
| Selector | ชื่อ | เลือก | ตัวอย่าง |
|---|---|---|---|
A > B | Child combinator | B เป็นลูกโดยตรงของ A | ul > li |
A B | Descendant combinator | B เป็นหลานทุกระดับของ A | ul li (รวม li ใน ol ใน ul) |
Combinators อื่นๆ:
A + B- Adjacent sibling (B ติด A ทันที)A ~ B- General sibling (B หลัง A ใดๆ)A || B- Column combinator (ตาราง)