CSS Selectors

The means by which you access one or more elements on the page is called selection, and as we saw earlier, the part of a CSS rule that does this is known as a selector. As you might expect, there are many different varieties of selector.

The Type Selector

The type selector specifies the HTML element to style, such as <p> or <i>. For example, the following rule will ensure that all text within <p>...</p> tags is fully justified:

p { text-align:justify; }

The Descendant Selector

Descendant selectors let you apply styles to elements that are contained within other elements. For example, the following rule sets all text within <b>...</b> tags to red, but only if they occur within <p>...</p> tags (like this: <p><b>Hello</b> there</p>):

p b { color:red; }

Descendant selectors can continue nesting indefinitely, so the following is a perfectly valid rule to make bold text inside a list element of an unordered list appear in blue:

ul li b { color:blue; }

As a practical example, suppose you want to use a different numbering system than the default for an ordered list that is nested within an unordered list. You can achieve this in the following way, which will replace the default numbering (starting from 1) with lowercase letters (starting from a):

<!DOCTYPE html>
<html>
    <head>
        <style>
            ul ol { list-style-type:lower-alpha; }
        </style>
    </head>
    <body>
        <ol>
            <li>One</li>
            <li>Two</li>
            <li>Three</li>
        </ol>
        <ul>
            <ol>
                <li>One</li>
                <li>Two</li>
                <li>Three</li>
            </ol>
        </ul>
    </body>
</html>

The result ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.