Combinators are a type of selectors which helps in combining various selectors.
As a side note if you use combinators, you also create a higher specificity. The rule with more information to it wins over rules with less information.
Adjacent Sibling Combinator (+)
General Sibling Combinator (~)
Child Combinator (>)
Descendant Combinator (space)
1. Adjacent Sibling Combinator (+)
The adjacent sibling combinator selects a element when the second element comes immediately after the first element. In adjacent sibling combinator both elements should have the same parent.
<!-- HTML -->
<article>
<h1>A heading</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa .</p>
<p>But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system</p>
</article>
/* CSS */
h1 + p {
font-weight: bold;
background-color: #333;
color: #fff;
padding: .5em;
}
In the above example the second paragraph will not be selected as adjacent sibling combinator only selects elements which are next or adjacent to the first element.
2. General Sibling Combinator (~)
General Sibling combinator is represented using (~
). The ~
key is above your tab
key. The general sibling combinator selects all the siblings of an element even if the second element is not directly adjacent to the first element.
<!-- HTML -->
<article>
<h1>A heading</h1>
<p>I am a paragraph.</p>
<div>I am a div</div>
<p>I am another paragraph.</p>
</article>
/* CSS */
h1 ~ p {
font-weight: bold;
background-color: #333;
color: #fff;
padding: .5em;
}
In the above example the styles will be applied to both the paragraphs.
3. Child Combinator (>)
The child combinator is only applied when a element is a direct child of the first element. The child combinator (>) is placed between two CSS selectors. Elements which are not direct descendent's of the parent element are not selected.
<!-- HTML -->
<ul>
<li>Unordered item</li>
<li>Unordered item
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol>
</li>
</ul>
/* CSS */
ul > li {
border-top: 5px solid red;
}
In the above example only the first two li
will have the top border.
4. Descendant Combinator (space)
The descendant combinator — typically represented by a single space ( ) character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector. Selectors that utilize a descendant combinator are called descendant selectors.
<!-- HTML -->
<div class="box">
<p>lorem ipsum</p>
<span>
<p>dolor semet</p>
</span>
</div>
/* CSS */
.box p {
color: red;
}
In the above example red color will be applied to both the p
tags.