CSS Combinators
CSS Combinators
CSS combinators define the relationship between selectors. They allow you to target elements based on how they are related in the HTML structure.
Descendant Selector
The descendant selector targets elements that are inside another element, at any level.
.card p {
color: #333;
}
This rule selects all <p> elements inside .card.
Child Selector
The child selector selects only direct children of an element.
.menu > li {
list-style: none;
}
This rule applies only to <li> elements that are direct children of .menu.
Adjacent Sibling Selector
The adjacent sibling selector selects the element that immediately follows another element.
h2 + p {
margin-top: 0;
}
This selects the first <p> that comes directly after an <h2>.
General Sibling Selector
The general sibling selector selects all siblings that come after an element.
h2 ~ p {
color: #666;
}
This selects all <p> elements that follow an <h2> within the same parent.
Combinator Example
Consider the following HTML structure:
<div class="card"> <h2>Title</h2> <p>First paragraph</p> <p>Second paragraph</p> </div>
.card > h2 {
color: #1f4bd8;
}
.card h2 + p {
font-weight: bold;
}
.card h2 ~ p {
color: #555;
}
Code Challenge
Goal: Use combinators to style related elements.
HTML:
<div class="article"> <h3>Heading</h3> <p>Intro text</p> <p>More content</p> </div>
Task:
- Color the heading
- Make only the first paragraph bold
- Change the color of all paragraphs after the heading
Try a Solution:
.article > h3 {
color: #1f4bd8;
}
.article h3 + p {
font-weight: bold;
}
.article h3 ~ p {
color: #555;
}
What’s Next?
Next, you will learn how pseudo-classes allow you to style elements based on their state.