Tech Junkie Blog - Real World Tutorials, Happy Coding!: CSS Parent Child Selectors

Friday, August 9, 2019

CSS Parent Child Selectors

A big part of web development is dealing with the DOM (Document Object Model) the DOM is organized in a hierarchical order.  You locate an element in the DOM by traversing through the DOM tree.  For instance if you have an ordered list there's a natural hierarchical order to it.

Let's say you have the following markup

        <ul>
            <li>item 1</li>
            <li>
                <ul>
                    <li>sub item 1</li>
                    <li>sub item 2</li>
                    <li>sub item 3</li>
                </ul>
            </li>
            <li>item 2</li>
            <li>item 3</li>
        </ul>



If you look at the elements console after pressing F12 you will see that list is organized in tree like structure.

I am using brackets as my IDE so you can ignore the data-brackets-id element, it's kind of a nice feature on the live preview feature.

Anyways let's get back to the parent child relationship.  So the first level of the list is the top parent, then the next level is the children.  The the sub items are the kids who decided to have children of their own.  Let's add some more relationships by adding the <strong> tag to the fist level.

Like so

        <ul>
            <li><strong>item 1</strong></li>
            <li>
                <ul>
                    <li>sub item 1</li>
                    <li>sub item 2</li>
                    <li>sub item 3</li>
                </ul>
            </li>
            <li><strong>item 2</strong></li>
            <li><strong>item 3</strong></li>
        </ul>



















The way to access the child element in the list is with the > symbol.  So let's demonstrate this by changing the color of the item that's bolded to green with this declaration


ul > strong {color:green}

















Ooops that didn't work.  The reason it didn't work is because for each relationship, there's a need to have a > symbol.  So the style that would work is actually ul > li > strong {color: green} not ul> strong {color:green} because the strong tag actually is a direct child of the li tag not the ul tag















That's more like it.

Here is the entire markup

<html>
    <head>
        <style>
            ul > li >  strong {color:green}
        </style>
    </head>
    <body>
        <ul>
            <li><strong>item 1</strong></li>
            <li>
                <ul>
                    <li>sub item 1</li>
                    <li>sub item 2</li>
                    <li>sub item 3</li>
                </ul>
            </li>
            <li><strong>item 2</strong></li>
            <li><strong>item 3</strong></li>
        </ul>
    </body>
</html>

Previous: CSS HTML Attribute Selectors

No comments:

Post a Comment

Search This Blog