How to combine selectors in CSS
Cascading Style Sheets (CSS) offers many options to style web pages. CSS uses selectors to define the classes to which a particular style is applied. These selectors can also be combined for varied uses. The common combinations are highlighted below.
Descendent combinator
Descendent combinator combines selectors with a space.
A B {
/* CSS Code */
}
Here, all selectors B which are a A will have the defined style.
Child combinator
Child combinator combines selectors with a greater than symbol >.
A > B {
/* CSS Code */
}
Here, all selectors B enclosed directly within A will have the defined style.
Next sibling combinator
Next sibling combinator combines selectors with a plus sign +.
A + B {
/* CSS Code */
}
Here, the selector B that comes immediately after A will have the defined style.
Following sibling combinator
Following sibling combinator combines selectors with a plus sign ~.
A ~ B {
/* CSS Code */
}
This is similar to the next sibling combinator, except that it is not necessary for the sibling B to come immediately after A.
Code
The following example shows how we can use the selectors above on HTML elements.
Free Resources