What is a CSS Selector

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 CSS selectors, which are patterns used to target specific HTML elements on a webpage.

Introducing the Cascading Style Sheet (CSS)

CSS is short for Cascading Style Sheet, it controls the appearance of the HTML components, such as the element's 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:

html
1<p style="color: red;">Lorem ipsum dolor sit amet . . .</p>

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

html
1<p style="color: red; text-decoration: underline;">Lorem ipsum . . .</p>

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.

A better option would be assigning the same set of styles to different elements. This can be achieved by creating a <style> element in the <head> section like this:

html
1<!doctype html>
2<html lang="en">
3  <head>
4    <meta charset="UTF-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6    <title>Document</title>
7
8    <style>
9      p {
10        color: red;
11        text-decoration: underline;
12      }
13    </style>
14  </head>
15
16  <body>
17    <p>. . .</p>
18    <p>. . .</p>
19    <p>. . .</p>
20  </body>
21</html>

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

text
1.
2├── index.html
3└── style.css
css
1p {
2  color: red;
3  text-decoration: underline;
4}
html
1<!doctype html>
2<html lang="en">
3  <head>
4    <meta charset="UTF-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6    <title>Document</title>
7
8    <link rel="stylesheet" href="style.css" />
9  </head>
10
11  <body></body>
12</html>

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

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 example CSS code.

css
1p {
2  color: red;
3  text-decoration: underline;
4}

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?

html
1<body>
2  <div>
3    <p>Lorem ipsum . . .</p>
4    <p>Lorem ipsum . . .</p>
5  </div>
6  <section>
7    <p>Lorem ipsum . . .</p>
8  </section>
9</body>

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. The id must be unique across the entire document.

html
1<body>
2  <div>
3    <p id="first-paragraph"></p>
4    <p id="second-paragraph">. . .</p>
5  </div>
6  <section>
7    <p id="third-paragraph">. . .</p>
8  </section>
9</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
1#first-paragraph {
2  color: red;
3}
4
5#second-paragraph {
6  color: blue;
7}
8
9#third-paragraph {
10  color: green;
11}
Open demo in new tab

However, as you can see, this method still requires micromanaging individual elements, as there cannot be two elements with the same id in one HTML document.

So instead, you can use class to categorize different elements, regardless of their types.

html
1<body>
2  <div>
3    <p class="red-text">. . .</p>
4    <p class="blue-text">. . .</p>
5  </div>
6  <section>
7    <p class="blue-text">. . .</p>
8  </section>
9</body>

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.

css
1.red-text {
2  color: red;
3}
4
5.blue-text {
6  color: blue;
7}
Open demo in new tab

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
1<body>
2  <div>
3    <p class="red-text bold">. . .</p>
4    <p class="blue-text underline">. . .</p>
5  </div>
6  <section>
7    <p class="blue-text bold underline">. . .</p>
8  </section>
9</body>
css
1.red-text {
2  color: red;
3}
4
5.blue-text {
6  color: blue;
7}
8
9.bold {
10  font-weight: bold;
11}
12
13.underline {
14  text-decoration: underline;
15}
Open demo in new tab

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.

html
1<h1 class="red-text">Heading</h1>
2<p class="red-text">. . .</p>
3<p class="blue-text">. . .</p>
css
1p.red-text {
2  color: red;
3}
Open demo in new tab

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
1<body>
2  <div>
3    <p>. . .</p>
4    <section>
5      <p>. . .</p>
6    </section>
7  </div>
8  <section>
9    <p>. . .</p>
10  </section>
11</body>

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.

css
1div p {
2  color: red;
3}
Open demo in new tab

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.

css
1div > p {
2  color: red;
3}
Open demo in new tab

select direct descendants

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

html
1<p>. . .</p>
2<span>. . .</span>
3<span>. . .</span>

+ selects the sibling directly after the specific element:

css
1p + span {
2  color: red;
3}

select direct sibling

~ selects all siblings:

css
1p ~ span {
2  color: red;
3}

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.

css
1.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

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 is given 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
1a {
2  color: blue;
3}
4
5a:hover {
6  color: darkblue;
7}
8
9a:active {
10  color: red;
11}
12
13a:visited {
14  color: purple;
15}
Open demo in new tab

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

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

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

html
1<p class="cap-drop">Lorem ipsum dolor sit . . .</p>
css
1.cap-drop::first-letter {
2  font-size: xx-large;
3  float: left;
4  margin-right: 5px;
5}
Open demo in new tab

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

css
1* {
2  font-family: Arial, sans-serif;
3}

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

css
1h1,
2h2,
3h3,
4p {
5  font-family: Arial, sans-serif;
6}

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
1p[lang] {. . .}

Or specify a desired value for that attribute.

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

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