Combinators are used to explain the relationship between the selectors ( they do not modify the specificity though )
Types of combinators
- Descendant ( space )
- Child ( > )
- General sibling ( ~ )
- Adjacent sibling ( + )
Descendant :
We can write styles for all descendant of the parent element using empty space as the combinator
eg.
<div id="container">
<p>hello 1</p>
<p> hello 2</p>
<div>
<p>Hello 3</p>
</div>
To target all p tags in the parent #container div we can use empty space combinator
#container p{
color: yellow;
}
Above will apply the color yellow to all p tags
Child:
the child combinator ( > ) will select only the direct children
eg.
#container > p{
color: yellow;
}
Above will only select the first 2 p tags which are direct children of the container div and not the 3rd p tag that is inside another div
Note: All children are descendants bit not all descendants are children
General Sibling:
General siblings are selected using ~ symbol, this will select all siblings of the selected element.
e.g
<body>
<div id="container">
<p>hello 1</p>
<p> hello 2</p>
<div>
<p>Hello 3</p>
</div>
<p>hello 4</p>
<p>hello 5</p>
</body>
In above example, paragraph 4 and 5 are siblings of the container since they have same parent : body, we can select those using ~
#container ~ p{
color : green;
}
Adjacent Sibling :
Adjacent sibling is selected using + symbol , it select only the next sibling and not others.
eg.
#container + p{
color : green;
}
Above will only select the paragraph 4 since it is adjacent sibling of container and not 5
Leave a Reply