CSS Combinators

DevJunctionPoint
0

 




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

Descendant Selector

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

div p {
    color: rgb(255, 0, 60);
    background-color: aquamarine;
}


Child Selector

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

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

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


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. 

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

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



General Sibling Selector:

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

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



example:
index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Combinators</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <h1>CSS Combinators</h1>

    <div>
        <p>Lorem ipsum dolor sit amet.</p>
        <p>Lorem ipsum dolor sit amet.</p>
        <section>
            <p>Lorem ipsum dolor sit amet.</p>
        </section>
        <p>Lorem ipsum dolor sit amet.</p>
    </div>
    <p>Lorem ipsum dolor sit amet.</p>
    <p>Lorem ipsum dolor sit amet.</p>
</body>

</html>

style.css

* {
    box-sizing: border-box;
}

h1 {
    text-shadow: 2px 2px 4px red;
    margin-bottom: 30px;
    text-align: center;
}

div p {
    color: rgb(255, 0, 60);
    background-color: aquamarine;
}

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

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

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

Post a Comment

0Comments

Do leave your comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!
To Top