css - Combinators
CSS combinators allow you to select elements based on their relationships in the HTML structure. By using combinators, you can style elements based on hierarchy and positioning within the DOM. CSS offers four main types of combinators: descendant, child, adjacent sibling, and general sibling.
This guide covers:
Descendant Combinator ( )
Child Combinator (>)
Adjacent Sibling Combinator (+)
General Sibling Combinator (~)
1. Descendant Combinator ( )
The descendant combinator is a space ( ) between two selectors and targets all nested elements inside another element, regardless of depth.
Example
/* Selects all <p> elements inside <div> elements */
div p {
color: blue;
}
In this example, all <p> elements inside any <div> will be styled with a blue color, regardless of how deeply they are nested.
HTML Example
<div>
<p>This paragraph is blue.</p>
<section>
<p>This paragraph is also blue.</p>
</section>
</div>
Both <p> tags will inherit the blue color because they are descendants of the <div>.
2. Child Combinator (>)
The child combinator selects elements that are direct children of a specific parent element.
Example
/* Selects only direct child <p> elements within <div> elements */
div > p {
color: green;
}
This will style only the <p> elements that are direct children of <div>. Nested <p> tags inside other elements within the <div> are not affected.
HTML Example
<div>
<p>This paragraph is green.</p>
<section>
<p>This paragraph is not affected.</p>
</section>
</div>
Only the first <p> tag will be green, as it’s a direct child of the <div>.
3. Adjacent Sibling Combinator (+)
The adjacent sibling combinator selects an element that immediately follows another element.
Example
/* Selects the <p> element that immediately follows an <h2> */
h2 + p {
font-weight: bold;
}
Here, only the first <p> element immediately after an <h2> will be bold. If there are multiple <p> elements, only the one directly after the <h2> is styled.
HTML Example
<h2>Heading</h2>
<p>This paragraph is bold.</p>
<p>This paragraph is not bold.</p>
Only the first <p> after <h2> is affected by the styling.
4. General Sibling Combinator (~)
The general sibling combinator selects all siblings of a specified element, as long as they share the same parent.
Example
/* Selects all <p> elements that are siblings of an <h2> */
h2 ~ p {
color: red;
}
In this example, every <p> element that shares a parent with <h2> will be styled with a red color.
HTML Example
<h2>Heading</h2>
<p>This paragraph is red.</p>
<p>This paragraph is also red.</p>
<div>
<p>This paragraph is not affected because it’s in a different container.</p>
</div>
The <p> elements that are siblings of <h2> (within the same container) will be red.