【My Study Note】Combination selectors
Combination selectors
Sometimes you want to apply the same styling to different elements or to different groups of elements. CSS makes it possible to combine more than one selector so that you can apply rules to elements based on their relationship with one another. You do this with combination selectors, and there are four main types.
4 Selectors
- Descendant selectors (Using Space)
- Child Selectors (>)
- General Sibling Selectors (~)
- Adjacent Sibling Selectors (+)
Descendant selectors (Using Space)
/* This specify the all p element of the parent element which is "class: name" */
.name p {}
Child Selectors (>)
Child selectors on the other hand are more specific than descendant selectors.
They only select the only immediate children.
<div class="name">
<!-- Only this would be selected -->
<h1>Latest News</h1>
<div>
<h1>Weather forecast</h1>
</div>
</div>
.name > h1 {
color: white;
}
General Sibling Selectors (~)
<div class="name">
<h1>Latest News</h1>
<div>
<h1>Weather forecast</h1>
<!-- These 2 p elements down below would be selected -->
<p>Happy</p>
<p>Awesome</p>
</div>
</div>
h1 ~ p {
color: white;
}
This applies rules to all the selectors of the same type that follow the first type. Literally, they select the siblings.
Adjacent Sibling Selectors (+)
<div class="name">
<h1>Latest News</h1>
<div>
<h1>Weather forecast</h1>
<!-- Only "Happy" would be selected -->
<p>Happy</p>
<p>Awesome</p>
</div>
</div>
h1 + p {
color: white;
}
In comparison to sibling selectors, you can use adjacent sibling selectors to target only the first or adjacent element that follows another element.