🎨 CSS Selector Combinations Explained
When we style a website using CSS, sometimes multiple elements share the same tag (like many <p> or <li>). Giving each one a different class or ID quickly becomes messy.
That’s why CSS provides different selector combinations to target elements more precisely.
🔹 1. Grouping Selector (,)
Used to apply the same style to multiple selectors at once.
👉 Both <h1> and <h2> will turn blueviolet.
🔹 2. Child Selector (>)
Selects only the direct child of a parent element.
👉 Only the <p> that is a direct child of .box will turn firebrick.
⚠️ Grandchildren (nested deeper) will not be affected.
🔹 3. Descendant Selector (space)
Selects all descendants, no matter how deep inside.
👉 All <li> inside .box will turn blue, whether they are one level down or multiple levels deep.
🔹 4. Chaining Selector (no spaces)
Targets elements that match multiple conditions at once.
👉 Only <li> elements with the class "done" will turn seagreen.
This ignores <p class="done"> or any other element.
🔹 5. Combining Different Methods
You can combine descendant + chaining (and more) for extra precision.
👉 Only <p> elements with class "done" that are inside a <ul> will get the smaller font size.
Other <p class="done"> outside a <ul> will not be affected.
📝 Quick Summary
-
,(comma) → Apply same style to multiple selectors. -
>→ Direct child only. -
space→ Any descendant inside the parent. -
Chaining (e.g., li.done) → Match multiple conditions on the same element.
-
Combining → Mix these methods for very specific targeting.
Comments
Post a Comment