Delve into CSS Selectors
Tags: css, tutorial, webdev, beginners
Published: 2023-10-09 14:31:39

> This course has been migrated to www.thedevspace.io

Let's take a closer look at the example CSS code from the [previous article](https://www.thedevspace.io/course/htmlcss-html-elements).

```css
p {
    color: red;
    text-decoration: underline;
}
```

`p` is a selector that selects all `<p>` elements in the [HTML document](https://www.thedevspace.io/course/htmlcss-html-elements). 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?

```html
<body>
    <div>
        <p>Lorem ipsum . . .</p>
        <p>Lorem ipsum . . .</p>
    </div>
    <section>
        <p>Lorem ipsum . . .</p>
    </section>
</body>
```

## The `class` and `id` selectors

To answer this question, we must discuss two essential [HTML attributes](https://www.thedevspace.io/course/htmlcss-html-elements), `id` and `class`. In an HTML document, each element can be assigned an `id`, which must be unique throughout the entire document.

```html
<body>
    <div>
        <p id="first-paragraph"></p>
        <p id="second-paragraph">. . .</p>
    </div>
    <section>
        <p id="third-paragraph">. . .</p>
    </section>
</body>
```

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.

```css
#first-paragraph {
    color: red;
}

#second-paragraph {
    color: blue;
}

#third-paragraph {
    color: green;
}
```

![id selector](https://www.ericsdevblog.com/courses/html-css/2/images/id-selector.png)

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.

```html
<body>
    <div>
        <p class="red-text">. . .</p>
        <p class="blue-text">. . .</p>
    </div>
    <section>
        <p class="blue-text">. . .</p>
    </section>
</body>
```

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.

```css
.red-text {
    color: red;
}

.blue-text {
    color: blue;
}
```

![class selector](https://www.ericsdevblog.com/courses/html-css/2/images/class-selector.png)

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.

```html
<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>
```

```css
.red-text {
    color: red;
}

.blue-text {
    color: blue;
}

.bold {
    font-weight: bold;
}

.underline {
    text-decoration: underline;
}
```

![multiple classes](https://www.ericsdevblog.com/courses/html-css/2/images/multiple-classes.png)

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`.

```html
<h1 class="red-text">Heading</h1>
<p class="red-text">. . .</p>
<p class="blue-text">. . .</p>
```

```css
p.red-text {
    color: red;
}
```

![select element under class](https://www.ericsdevblog.com/courses/html-css/2/images/element-under-class.png)

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:

```html
<body>
    <div>
        <p>. . .</p>
        <section>
            <p>. . .</p>
        </section>
    </div>
    <section>
        <p>. . .</p>
    </section>
</body>
```

This HTML document will create a tree structure like this:

![DOM](https://www.ericsdevblog.com/courses/html-css/2/images/dom-tree.excalidraw.png)

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](https://www.ericsdevblog.com/courses/html-css/2/images/dom-relation.excalidraw.png)

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.

```css
div p {
    color: red;
}
```

![select descendants](https://www.ericsdevblog.com/courses/html-css/2/images/select-descendants.png)

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

![select descendants](https://www.ericsdevblog.com/courses/html-css/2/images/dom-select-descendants.excalidraw.png)

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.

```css
div > p {
    color: red;
}
```

![select children](https://www.ericsdevblog.com/courses/html-css/2/images/select-children.png)

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

```html
<p>. . .</p>
<span>. . .</span>
<span>. . .</span>
```

`+` selects the sibling directly after the specific element:

```css
p + span {
    color: red;
}
```

![select direct sibling](https://www.ericsdevblog.com/courses/html-css/2/images/select-direct-sibling.png)

`~` selects all siblings:

```css
p ~ span {
    color: red;
}
```

![select siblings](https://www.ericsdevblog.com/courses/html-css/2/images/select-siblings.png)

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`.

```css
.intro p {. . .}
```

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.

```css
a {
    color: blue;
}

a:hover {
    color: darkblue;
}

a:active {
    color: red;
}

a:visited {
    color: purple;
}
```

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](https://www.w3schools.com/css/css_pseudo_classes.asp) from W3Schools.

Pseudo-element selectors, on the other hand, are used to select parts of an element. For example, [drop cap](https://en.wiktionary.org/wiki/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>`.

```html
<p><span>L</span>orem ipsum dolor sit . . .</p>
```

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

```html
<p class="cap-drop">Lorem ipsum dolor sit . . .</p>
```

```css
.cap-drop::first-letter{
    font-size: xx-large;
    float: left;
    margin-right: 5px;
}
```

![cap drop](https://www.ericsdevblog.com/courses/html-css/2/images/cap-drop.png)

`.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](https://www.w3schools.com/css/css_pseudo_elements.asp) 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.

```css
* {
  font-family: Arial, sans-serif;
}
```

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 (`,`).

```css
h1, h2, h3, p {
  font-family: Arial, sans-serif;
}
```

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

```css
p[lang] {. . .}
```

Or specify a desired value for that attribute.

```css
p[lang="en"] {. . .}
```

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](https://www.thedevspace.io/course/htmlcss-color).

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