Combinators & Attribute Selectors
Target elements based on their relationships and their attributes — precision selecting.
What you will learn
- Use descendant, child and sibling combinators
- Select by attribute
- Write precise, intentional selectors
Combinators — selecting by relationship
| Selector | Selects |
|---|---|
div p | Any p inside a div (descendant) |
div > p | A p that is a direct child of a div |
h2 + p | The p immediately after an h2 |
h2 p~ | All p siblings after an h2 |
<style>
.menu a { color:#4338ca; } /* all links inside .menu */
.menu > a { font-weight: 700; } /* only direct-child links */
h3 + p { color:#06b6d4; font-style: italic; } /* p right after an h3 */
</style>
<div class="menu"><a href="#">Direct child link</a></div>
<h3>A heading</h3>
<p>I am right after the heading (styled).</p>
<p>I am a later paragraph (not styled by + ).</p>Combinators select elements by their relationship to other elements, using the space or symbol between two selectors:
.menu a(a space = descendant) — matches any link anywhere inside.menu, no matter how deeply nested..menu > a(the>= direct child) — matches only links that are an immediate child of.menu, not ones buried deeper.h3 + p(the+= adjacent sibling) — matches only the one paragraph that comes immediately after anh3. That is why the first paragraph is styled cyan and italic, but the second paragraph (further down) is not.
Attribute selectors
Select elements by their attributes with square brackets — very handy for forms.
<style>
input[type="text"] { border:2px solid #4338ca; padding:8px; border-radius:6px; }
input[type="email"] { border:2px solid #06b6d4; padding:8px; border-radius:6px; }
a[target="_blank"]::after { content: " ↗"; }
</style>
<input type="text" placeholder="text input"><br><br>
<input type="email" placeholder="email input"><br><br>
<a href="#" target="_blank">External link</a>The square brackets let you target elements by an attribute and its value. input[type="text"] matches only text inputs and gives them an indigo border, while input[type="email"] matches only email inputs and gives them a cyan one — even though both are <input> tags. The last rule, a[target="_blank"]::after, finds links that open in a new tab and automatically appends a small ↗ arrow after them. Attribute selectors are especially handy for forms, where inputs share a tag but differ by type.
Q. What does div > p select?
✍️ Practice
- Style only the direct-child links of a menu differently from nested links.
- Style text inputs and email inputs differently using attribute selectors.
🏠 Homework
- Use attribute selectors to style every input type on your contact form individually.