Combinators คืออะไร?
สมมุติว่าในเว็บไซต์หนึ่งหน้ามี paragraph หรือ tag <p>
อยู่มากมาย ที่อยู่ทั้ง แถบด้านข้าง และ ส่วนเนื้อหาหลัก
แล้วถ้าหากว่าเราอยากจะตกแต่งแค่ paragraph ที่อยู่ในแถบด้านข้างหล่ะ Combinators จึงเข้ามามีบทบาทนี้
แนะนำ Combinators
Result
Combinator จะแบ่งออกเป็น 4 combinators ด้วยกัน ซึ่งจะประกอบด้วย
- Descendant combinator (space)
- Child combinator (>)
- Next sibling combinator (+)
- Subsequent-sibling combinator (~)
แต่จะลงรายละเอียดเฉพาะ Descendant combinator (space) กับ Child combinator (>) และสามารถดู Combinator ตัวอื่นๆอีกได้ที่นี่
Descendant combinator (space)
Descendant Combinator จะเลือก Elements "ทุกตัว" ที่อยู่ภายใน Element หลักที่กำหนด
ตัวอย่างการใช้ Descendant combinator
ตัวอย่างการใช้ Descendant combinator
index.html
Result
จากตัวอย่างจะเห็นว่า ทุก <p>
ที่อยู่ใน <div>
จะถูกเลือกถึงแม้ว่า <p>
ที่อยู่ใน <section>
ก็ตาม ซึ่งก็จะอธิบายได้ว่า style ควรใช้ได้เฉพาะกับแท็ก <p>
ที่อยู่ใน <div>
เท่านั้น
Child combinator (>)
Child Combinator จะเลือก Elements ที่เป็นเฉพาะ Element ลูกของ Element หลักเท่านั้น
ตัวอย่างการใช้ Child combinator
ตัวอย่างการใช้ Child combinator
index.html
Result
จากตัวอย่าง Child combinator จะเลือกเฉพาะ <p>
ที่อยู่ใน <div>
และไม่เลือก <p>
ที่อยู่ใน <section>
ซึ่งก็จะอธิบายได้ว่า style ควรใช้ได้เฉพาะกับแท็ก <p>
ที่อยู่ใน <div>
เท่านั้น