DEV Community

Cover image for Delve into CSS Selectors
Eric Hu
Eric Hu

Posted on • Updated on • Originally published at thedevspace.io

Delve into CSS Selectors

This course has been migrated to www.thedevspace.io

Let's take a closer look at the example CSS code from the previous article.

p {
    color: red;
    text-decoration: underline;
}
Enter fullscreen mode Exit fullscreen mode

p is a selector that selects all <p> elements in the HTML document. The styles defined inside the curly braces ({}) will be assigned to all the selected elements.

However, what if you have a more complex HTML structure? For example, here we have two blocks, <div> and <section>, each with its own paragraphs. What should you do if you need the paragraphs to have different styles?

<body>
    <div>
        <p>Lorem ipsum . . .</p>
        <p>Lorem ipsum . . .</p>
    </div>
    <section>
        <p>Lorem ipsum . . .</p>
    </section>
</body>
Enter fullscreen mode Exit fullscreen mode

The class and id selectors

To answer this question, we must discuss two essential HTML attributes, id and class. In an HTML document, each element can be assigned an id, which must be unique throughout the entire document.

<body>
    <div>
        <p id="first-paragraph"></p>
        <p id="second-paragraph">. . .</p>
    </div>
    <section>
        <p id="third-paragraph">. . .</p>
    </section>
</body>
Enter fullscreen mode Exit fullscreen mode

You can then use an id selector to give each paragraph a unique style. An id selector starts with a hash character (#), followed by the id of the element you wish to select.

#first-paragraph {
    color: red;
}

#second-paragraph {
    color: blue;
}

#third-paragraph {
    color: green;
}
Enter fullscreen mode Exit fullscreen mode

id selector

However, as you can see, this method also requires micromanaging individual elements. So, instead, you can use class to categorize different HTML elements, regardless of their types.

<body>
    <div>
        <p class="red-text">. . .</p>
        <p class="blue-text">. . .</p>
    </div>
    <section>
        <p class="blue-text">. . .</p>
    </section>
</body>
Enter fullscreen mode Exit fullscreen mode

Next, use class selectors to select HTML elements under that particular class. class selectors start with a dot (.), followed by the class you wish to select.

.red-text {
    color: red;
}

.blue-text {
    color: blue;
}
Enter fullscreen mode Exit fullscreen mode

class selector

Individual HTML elements can also be placed under multiple classes separated by space characters. This enables you to create different combinations. For example, you can make the text bold and displayed in red by assigning the element to red-text and bold classes.

<body>
    <div>
        <p class="red-text bold">. . .</p>
        <p class="blue-text underline">. . .</p>
    </div>
    <section>
        <p class="blue-text bold underline">. . .</p>
    </section>
</body>
Enter fullscreen mode Exit fullscreen mode
.red-text {
    color: red;
}

.blue-text {
    color: blue;
}

.bold {
    font-weight: bold;
}

.underline {
    text-decoration: underline;
}
Enter fullscreen mode Exit fullscreen mode

multiple classes

Lastly, it is possible to select elements of a particular type under a particular class. For example, this is how you can select all <p> elements with the class red-text.

<h1 class="red-text">Heading</h1>
<p class="red-text">. . .</p>
<p class="blue-text">. . .</p>
Enter fullscreen mode Exit fullscreen mode
p.red-text {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

select element under class

Notice that even though <h1> also has the class red-text, it remains unstyled, as p.red-text only selects the <p> elements with the red-text class.

The combinator selectors

When the browser renders a webpage, it creates a tree structure based on the HTML document. For example:

<body>
    <div>
        <p>. . .</p>
        <section>
            <p>. . .</p>
        </section>
    </div>
    <section>
        <p>. . .</p>
    </section>
</body>
Enter fullscreen mode Exit fullscreen mode

This HTML document will create a tree structure like this:

DOM

This is referred to as a DOM (Document Object Model) tree, meaning the elements will have hierarchical relations with each other. For instance, if we start from <body>, the parent, it has two children, <div> and <section>, who are siblings to each other.

DOM relations

You may utilize these relations between elements to select the desired components. These selectors are called combinator selectors.

For example, you can use a space character to select the descendants of an element.

div p {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

select descendants

Notice that two paragraphs, both direct and indirect descendants of <div> are selected.

select descendants

If the structure of the DOM tree gets more complex, it can be challenging to keep track of everything. To minimize the risk of errors, you can use a child selector (>) to limit your selections to direct descendants only.

div > p {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

select children

Besides selecting descendants, you can also select siblings using + or ~ selectors.

<p>. . .</p>
<span>. . .</span>
<span>. . .</span>
Enter fullscreen mode Exit fullscreen mode

+ selects the sibling directly after the specific element:

p + span {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

select direct sibling

~ selects all siblings:

p ~ span {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

select siblings

You can combine different combinator selectors to create a complex selector such as div > p + span. However, this is not recommended as it is very easy to lose track of things.

Lastly, it is also possible to use class selectors along with combinator selectors. For example, you can select the <p> elements that are descendants of elements under the class .intro.

.intro p {. . .}
Enter fullscreen mode Exit fullscreen mode

In this case, the browser will start from elements under class intro, and then see if they have any paragraph elements as their descendants.

The pseudo-selectors

Pseudo-selectors are used to target HTML elements based on their specific states or parts. There are two types of pseudo-selectors available: pseudo-class selectors and pseudo-element selectors.

Let's begin with the pseudo-class selectors. These selectors allow you to style an element based on its state. For instance, let's consider the <a> element, which represents a hyperlink in a webpage. Initially, it appears blue. Once clicked, it turns red, and after being visited, it turns purple. Despite being the same element, different styles are applied to it depending on its state.

Pseudo-class selectors are the key to achieving this effect. They target elements only when they are in specific states. The hyperlink element starts without any state. When you move the cursor over it, it is given the :hover state, and when clicked, it acquires the :active state. Lastly, after being visited, it is given the :visited state. These states allow you to apply different styles to the same element under different circumstances. This feature is crucial for frontend design because it enables the webpage to respond dynamically to user actions.

a {
    color: blue;
}

a:hover {
    color: darkblue;
}

a:active {
    color: red;
}

a:visited {
    color: purple;
}
Enter fullscreen mode Exit fullscreen mode

There are many other pseudo-class selectors available, and different elements may have different states. We are not going to cover all of them in this chapter, but if you are interested, here is a list of all pseudo-class selectors from W3Schools.

Pseudo-element selectors, on the other hand, are used to select parts of an element. For example, drop cap is a common type of decoration for many webpages used to indicate the beginning of an article. Without the pseudo-element selector, you will have to wrap the first letter of the paragraph inside a <span> element and then apply styles to that <span>.

<p><span>L</span>orem ipsum dolor sit . . .</p>
Enter fullscreen mode Exit fullscreen mode

However, there is a shortcut. You can simply use the ::first-letter selector, which selects the first letter of the element.

<p class="cap-drop">Lorem ipsum dolor sit . . .</p>
Enter fullscreen mode Exit fullscreen mode
.cap-drop::first-letter{
    font-size: xx-large;
    float: left;
    margin-right: 5px;
}
Enter fullscreen mode Exit fullscreen mode

cap drop

.cap-drop locates the elements under the class cap-drop, and then ::first-letter locates the first letter of the selected elements. Notice that pseudo-element selectors start with two colons (::). This saves you the trouble of isolating the first letter with a <span> element.

There are other pseudo-element selectors available in CSS. Please visit the linked page for details.

Other selectors

Sometimes, you might need to apply the same styles to all elements in the webpage, such as unifying the font or text alignment. In this case, instead of repeating the same style for all elements, you can simply use the universal selector (*), which matches all elements in the webpage.

* {
  font-family: Arial, sans-serif;
}
Enter fullscreen mode Exit fullscreen mode

Or, if you wish to select only a subset of elements, you can also use a group selector. It allows you to combine multiple selectors together, separated by a comma (,).

h1, h2, h3, p {
  font-family: Arial, sans-serif;
}
Enter fullscreen mode Exit fullscreen mode

Lastly, CSS also allows you to select elements based on attributes. For instance, the following example selects all <p> elements with the attribute lang.

p[lang] {. . .}
Enter fullscreen mode Exit fullscreen mode

Or specify a desired value for that attribute.

p[lang="en"] {. . .}
Enter fullscreen mode Exit fullscreen mode

And now, only the <p> elements with the attribute lang="en" will be selected.

Conclusion

In this article, we discussed how to select elements using CSS selectors. Next, we are going to talk more about what to do with the selected element in the next chapter.

Please visit www.thedevspace.io for the rest of this course.

Top comments (0)