DEV Community

Cover image for Introducing CSS Selectors
TheDevSpace
TheDevSpace

Posted on • Originally published at thedevspace.io

Introducing CSS Selectors

Now that we have covered some basic HTML tags, it's time to explore how to enhance their visual presentation using CSS. In this lesson, we will start with the CSS selector, which is the pattern used to locate specific HTML elements on a webpage.

Cascading Style Sheet (CSS)

CSS is short for Cascading Style Sheet, it controls the appearance of the HTML components, such as the the color, spacing, size, and more.

Recall that the default appearance of an HTML element can be altered by specifying a style attribute. For example, if you want to change the color of a paragraph, this is what you can do:

<p style="color: red;">Lorem ipsum dolor sit amet . . .</p>
Enter fullscreen mode Exit fullscreen mode

The style declaration statement follows the format <key>: <value>;. You may define another style after the semicolon (;).

<p style="color: red; text-decoration: underline;">Lorem ipsum . . .</p>
Enter fullscreen mode Exit fullscreen mode

However, this is an inefficient way of managing styles, as a real-life webpage could have hundreds of different elements. It will become a disaster if you try to micromanage all of them.

In practice, you are likely to have multiple elements that share the same appearance, and it makes more sense to assign the same set of styles to them. This can be achieved by creating a <style> element in the <head> section like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <style>
      p {
        color: red;
        text-decoration: underline;
      }
    </style>
  </head>

  <body>
    <p>. . .</p>
    <p>. . .</p>
    <p>. . .</p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Alternatively, you could create an separate CSS document, such as style.css, and then import the document into your HTML file.

.
├── index.html
└── style.css
Enter fullscreen mode Exit fullscreen mode

style.css

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

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <link rel="stylesheet" href="style.css" />
  </head>

  <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

This is how you can add CSS code to your webpage, and as you can see, both paragraphs have been assigned the same style.

Note: Here is a small tip when designing your webpages. You can check the styles assigned to each element through the developer tools built into your browser. For example, if you use Google Chrome, right-click on the webpage and select Inspect.

inspect element

A side panel should pop up, displaying the source code. You can select any element to check what CSS styles are applied. You can also uncheck certain styles to see what would happen to the page without it.

developer tools

How to select HTML elements

Let's take a closer look at the CSS code demo above.

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 then 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 first discuss two essential HTML attributes, id and class. In an HTML document, each element can be assigned an id.

<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

The id must be unique across the entire document. For example, the following code is not allowed, because the first paragraphs have the same id.

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

After setting an appropriate id, 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

View Code Demo 🔗

However, as you can see, since there cannot be two elements with the same id, this method still requires us to micromanage individual elements.

So instead, you can use class to categorize different elements.

<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. A class selector starts 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

View Code Demo 🔗

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

View Code Demo 🔗

Lastly, it is possible to select elements of a particular type under the specified 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

View Code Demo 🔗

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.

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

View Code Demo 🔗

Notice that two paragraphs, both the 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

View Code Demo 🔗

select direct descendants

Besides selecting descendants, you can also select siblings using + and ~ 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 all 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 make mistakes.

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

There are two types of pseudo-selectors available: pseudo-class selectors and pseudo-element selectors.

The pseudo-class 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 a specific state.

The hyperlink element starts without any state. When you move the cursor over it, it is given the :hover state, and when clicked, it is given the :active state. Lastly, after being visited, it is acquires 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

View Code Demo 🔗

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 lesson, 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. They are 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 to select 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

View Code Demo 🔗

.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 rule 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. Different selectors in the groups are separated by commas (,).

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 you can also 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.

Further readings

This post was originally published at TheDevSpace. Everything you need to master web development, all in one place.

Top comments (0)