2.6. Advanced Selectors#

2.6.1. Grouping Selector#

In cases where you want to apply the same styling to multiple selectors you can group them up as shown in the example below using commas to separate each selector:

<html></html>
    <head>
       <style>
            h1, h2, p {
                text-align: center;
                color: red;
            }
       </style>
    <head>

    <body>
        <h1>Heading 1</h1>

        <h2>Heading 2</h2>
        
        <p>Paragraph</p>
    </body>
</html>

2.6.2. Descendant Selector#

To limit the scope of a selector to a particular parent tag you can use the descendant selector syntax which is a sequence of selectors separated by whitespace.

The example below selects all <p> elements nested inside <div> elements, including further descendents.

<html></html>
    <head>
       <style>
            p span{
                color: red;
                font-size: 20px;
            }
       </style>
    <head>

    <body>
        <h1>Toot Toot, Chugga Chugga, <span>Big Red</span> Car</h1>

        <p>Toot Toot, Chugga Chugga, <b><span>Big Red</span></b> Car</p>
        <p>We'll travel near and we'll travel far</p>
        <p>Toot Toot, Chugga Chugga, <span>Big Red</span> Car</p>
        <p>We're gonna ride the whole day long</p>
    </body>
</html>

2.6.3. Child Selector#

To limit the scope of a selector to the immediate content of a parent element you can use a child selector, which is a sequence of selectors separated by right angle brackets.

The following example selects all <span> elements that are immediate children of a <p> element.

<html></html>
    <head>
       <style>
            p > span{
                color: red;
                font-size: 20px;
            }
       </style>
    <head>

    <body>
        <h1>Toot Toot, Chugga Chugga, <span>Big Red</span> Car</h1>

        <p>Toot Toot, Chugga Chugga, <b><span>Big Red</span></b> Car</p>
        <p>We'll travel near and we'll travel far</p>
        <p>Toot Toot, Chugga Chugga, <span>Big Red</span> Car</p>
        <p>We're gonna ride the whole day long</p>
    </body>
</html>