I continue fixing my CSS weakness and today is time for the CSS Combinators.
Sometimes, we want to select elements without affecting others and understand how the relation between elements is the key.
The CSS Combinators help to write a better CSS selector using the relation as key, we have 4 types of Combinators.
- Descendant selector
- Child Selector
- Sibling Selector
- General Sibling
The Descendant selector
It matches all elements that are descendants of the element.
My example, we have 2 div with the sandbox class and contains p and additional divs with p.
<div class="sandbox">
<p>hello</p>
<div class="actions">
<p>close</p>
</div>
</div>
<div class="sandbox">
<p>adios</p>
<div class="actions">
<p>close</p>
</div>
</div>
For set the background color to all p inside of sandbox.
.sandbox p {
background-color: red;
}
it works, but not 100%, because others p inside of actions div have the background color.
So, If we want a rule that select all dependents elements then, use descendants selector.
But if I want only the p of sandbox and skip the others, then the child selector comes to rescue.
Child Selector (>)
The Child Selector use > and only select all direct children of the selector, so we can get our goal about only select the p of sandbox.
.sandbox > p {
background-color: red;
}
Nice, let continue!
Let's add a bit more stuff into my sandbox, h2 and few spans.
I want to select only the first span close to my h2.
<div class="sandbox">
<h2>
Angular 11
</h2>
<span>
Google Framework.
</span>
<span>ngInit</span>
<span>Observable</span>
<p>hello</p>
<div class="actions">
<p>close</p>
</div>
</div>
....
Sibling Selector
The Sibling selector use + and select the next element in place of selector, in our case h2 span
take the first span close to h2.
h2 + span {
background-color: pink;
display: block;
border-radius: 5px;
}
Work! but if I want all the remain span close to first have other look ? Tok Tok General Sibling!
General Sibling Selector
The General Sibling use ~ and select all siblings placed after it, so in our case we want all span close to span have other look, but my first span keep his style.
span ~ span {
background-color: gray;
display: block;
}
That's it! , that will give you a bit of help with CSS Combinators. If you enjoyed this post, share it and
Read more in MDN
Photo by Natalie Grainger on (Unsplash)
Top comments (3)
Hello, this part is very nice. Result, HTML and CSS and tha color in the writing. Supper, Thank you. Jana
I’m process of fix my css weakness, so I will continue writing about css learning process.
Buen artículo !