CSS Combinators
CSS combinators define the relationship between selectors. There are four different combinators in CSS:
- Descendant selector (space)
- Child selector (
>
) - Adjacent sibling selector (
+
) - General sibling selector (
~
)
1. Descendant Selector (space)
The descendant selector matches all elements that are descendants of a specified element.
Example:
<div class="descendant">
<p>This is a paragraph.</p>
<div class="inner">This is a descendant div.</div>
</div>
<style>
.descendant .inner {
background-color: #ffccbc;
padding: 10px;
}
</style>
This is a paragraph.
2. Child Selector (>
)
The child selector selects all elements that are the direct children of a specified element.
Example:
<div class="child">
<p>This is a paragraph.</p>
<div class="inner">This is a child div.</div>
</div>
<style>
.child > .inner {
background-color: #b3e5fc;
padding: 10px;
}
</style>
This is a paragraph.
3. Adjacent Sibling Selector (+
)
The adjacent sibling selector selects the element that is immediately adjacent to a specified element.
Example:
<div class="adjacent">
<p>This is a paragraph.</p>
<div class="inner">This is an adjacent sibling div.</div>
</div>
<style>
.adjacent + .inner {
background-color: #c8e6c9;
padding: 10px;
}
</style>
This is a paragraph.
4. General Sibling Selector (~
)
The general sibling selector selects all elements that are siblings of a specified element.
Example:
<div class="general">
<p>This is a paragraph.</p>
<div class="inner">This is a general sibling div.</div>
</div>
<style>
.general ~ .inner {
background-color: #ffcdd2;
padding: 10px;
}
</style>
This is a paragraph.
Conclusion
CSS combinators are powerful tools that define the relationship between different selectors, allowing for more precise and flexible styling of HTML elements. Understanding and using these combinators effectively can greatly enhance your CSS skills.