Parent/child elements

In this tutorial we will have a look at the parent/child relationship in CSS. All elements in an HTML document can be both parents and children, except for the body which can only be a parent. A div can be a child of the body or another div. A paragraph, heading, or other element can also be a child of the body or another div.

For example, if you place a <h1> heading inside a div, then the div is the heading’s parent and the body would be the div’s parent. This is called the parent/child relationship in CSS. We can use child selectors in CSS to apply styles to elements that are a child of another element such as a div or table. The image below illustrates the parent/child relationship in CSS.

The parent/child relationship in CSS.
The parent/child relationship in CSS.

The video below shows how to use child selectors in CSS to apply styles to child elements in an HTML web page. Watch the video below and then scroll down to see the HTML and CSS code.

Here’s the HTML code:

<html>
    <head>
        <title>Parent and child elements</title>
        <link rel="stylesheet" href="theme.css" type="text/css"/>
    </head>

    <body>
        <p>This text is not inside a div</p>

        <div>
            <p>This text is within a div</p>
        </div>

        <div class="mydiv">
            <p>This text is within a div with a class</p>
            <p class="mytext">This text has a class and is within a div with a class</p>
        </div>
    </body>
</html>

And here’s the CSS code (you can add to a separate theme.css stylesheet file or between <style> and </style> tags in your HTML code:

p{
    color: blue;
}

div p{
    color: red;
}

.mydiv p{
    color: purple;
}

.mydiv .mytext{
    color: green;
}