CSS Combinators


CSS Combinators

It explains the relation between multiple or single selector. There are four major combinators that we would be looking at here.

 

Descendant Selector

It selects all the elements to present inside another specified HTML element. 


Eg:

Css Combinators

 

Output:

Css Combinators

As you can see, div had 4 paragraphs and so, CSS rules were applied on all of them.

 

Child Selector

It selects only the first generation descendants of a specified element. 


Eg:

div>p {
            color: wheat;
            background-color: rebeccapurple;
        }

 

Just using this child selector in the same code the output changes to this:

Css Combinators

It happened because paragraph 3 is nested in the <section> tag and therefore is 2nd generation to the <div> selector and thus wasn’t selected.

 

Adjacent Sibling Selector

As the name suggests this selector only selects the adjacent element to the specified element. 


Eg:

div+p {
            color: wheat;
            background-color: rebeccapurple;
        }

 

Now, the <p> tag right after <div> ends, would be selected. So, the output would look like this:

Css Combinators

General Sibling Selector:

Unlike the adjacent selector, this one going to select all the <p> tags present after <div>.

 

Eg:

div~p {
            color: wheat;
            background-color: rebeccapurple;
        }

 

Output:

Css Combinators