Mastering CSS Selectors: A Comprehensive Guide
Tags: webdev, programming, css, beginners
Published: 2023-08-29 11:07:44

Cascading Style Sheets (CSS) is a fundamental language used for styling web pages, to enhance its appearance. It not only enhances the appearance of web pages but also precisely targets and styles specific HTML elements.

And fear not, because I’m here to guide you through this journey of applying styles to your HTML elements specifically using CSS selectors.

Let’s start!

## What are CSS Selectors?

CSS selectors are components of CSS that allow you to precisely target and apply styles to specific HTML elements on a web page. They determine which elements in the HTML document will be affected by the defined CSS rules.

Basically, selectors select the HTML element and apply the style to particularly that element.

Now let’s learn about the different types of CSS selectors.

## Basic Selectors
We have the following types of selectors in basic selectors.

- **Element Selector**

The element selector selects the elements based on their tag name.

For example, style the text color of all `<h1>` elements to red.

```
h1 {
  color: red;
}
```
Another example, align all `<p>` elements to the center.

```
p {
  text-align: center;
}
```
- **Class Selector**

The class selector selects the elements based on their class attribute. To select the elements with their class names use `.` just before the class name.

For example:

```
<h1 class="heading">This is a heading.</h1>
<p>This is a heading.</p>
<h2 class="heading">This is a also a heading.</h2>
```
Now we will select all the elements with the class “heading”.

```
.heading{
  color: red;
}
```
This will change the text color of all elements having a “heading” class.

- **ID Selector**

Since the id of an element is unique within a page, so the id selector selects a single element with a specific id attribute.

To select the element with its specific `id` use `#` character before the `id` name.

For example:

```
<h1 id="heading">This is a heading.</h1>
<p>This is a heading.</p>
```
Now we will select the specific element with the id “heading”.

```
#heading{
  color: red;
}
```
- **Universal Selector**

The universal selector selects all the elements on the page. To select all the elements of the web page just use a `*` sign.

For example:

```
* {
  margin: 0;
  padding: 0;
}
```
This will set the margin and padding of all the elements to 0.

## Combinators
We have the following types of combinators.

- **Descendant Combinator**

The Descendant Combinator selects elements that are descendants of a specified parent element.

But what are descendants?

Let me explain.

A descendant is simply an element that is inside another element. For example:

```
<div>
   <h1>This is a heading.</h1>
</div>
```
Here, `<h1>` is a descendent of `<div>`.

Now let’s get back to the descendent combinator.

The Descendant Combinator selects elements that are descendants of a specified parent element. The key idea here is that you should not be concerned about how deeply nested the descendant elements are inside the parent. Whether they are directly inside the parent or several levels deep, you can target all of them.

To select the descendent write the tag name, class attribute or id attribute of the parent element and after a space write the name of the descendent.

For example:

```
<section>
    <p>This is a paragraph.</p>
    <div>
      <p>This is another paragraph.</p>
    </div>
</section>
```
CSS:

```
section p {
  font-size: 20px;
}
```
This will change the font-size of all the `<p>` elements inside the `<section>` element, regardless of their level of nesting.

What if there’s another `<p>` element outside the `<section>` element?

```
<section>
    <p>This is a paragraph.</p>
    <div>
      <p>This is another paragraph.</p>
    </div>
</section>
<p>This is a paragraph outside the section element.</p>
```
Then the `font-size: 20px;` will not apply to the `<p>` outside of the `<section>` element.

A Descendant Combinator only selects the elements that are inside the parent element.

Select using `class` attribute:

```
<section class="header">
   <p>This is a paragraph.</p>
   <p>This is another paragraph.</p>
</section>
```
CSS:

```
.header p {
  font-size: 20px;
}
```
Select using `id` attribute:

```
<section id="header">
   <p>This is a paragraph.</p>
   <p>This is another paragraph.</p>
</section>
```
CSS:

```
#header p {
  font-size: 20px;
}
```
- **Child Combinator**

The child combinator selects elements that are a direct child of a specified parent element.

To select the direct child element use the `>` sign between the parent and child element.

For example:

```
<ul>
  <li>HTML</li>
  <li>CSS</li>
</ul>
```
CSS:

```
ul > li {
  font-weight: bold;
}
```
Let’s take another example.

```
<section>
    <p>This is a paragraph.</p>
    <div>
      <p>This is another paragraph.</p>
    </div>
</section>
```
Now, we want to change the text color of the `<p>` element of `<section>` element.

```
section > p {
  color: red;
}
```
Will it change the text color of `<p>` inside `<div>` element?

This will not.

Because we have used the `>` sign between `<section>` and `<p>`, so this style will only apply to the direct child `<p>` element of `<section>` element.

- **Adjacent Sibling Combinator**

The adjacent sibling combinator selects an element that is immediately preceded by a specific sibling element.

To put it simply, an adjacent sibling combinator selects an element that is an immediate sibling of the specified element, and there should be no other elements in between them.

The adjacent sibling combinator is represented by ‘+’ sign.

For example:

```
<h1>This is first heading.</h1>
<h2>This is second heading.</h2>
<h2>This is another second heading.</h2>
```
Now we want to change the text color of the first `<h2>` element, not all `<h2>` elements. Then we can use the adjacent sibling combinator.

```
h1 + h2{
  color: red;
}
```
The above style will only change the color of the `<h2>` element which is an immediate sibling of the `<h1>` element that means which comes just after the `<h1>` element and there should be no other element between them.

- **General Sibling Combinator**

The general sibling combinator selects sibling elements that share the same parent element and come after the specified element. This combinator does not require the selected element to be immediately preceded by the specified element.

The general sibling combinator is represented by the `~` symbol.

For example:

```
<p>I'm sibling paragraph of div.</p>
<div>
   <p>This is a paragraph inside a div.</p>
   <p>This is another paragraph inside a div.</p>
</div>
<p>I'm sibling paragraph of div.</p>
<h6>I'm sibling heading of div.</h6>
<p>I'm sibling paragraph of div.</p>
```
Now suppose we want to style all the sibling `<p>` elements of `<div>` element that comes after the `<div>` element.

```
div ~ p {
  color: red;
}
```
The above style will not change the style of `<p>` element that is before the `<div>` element because the general sibling combinator selects sibling elements that come after the specified element and here specified element is `<div>` .

## Pseudo-Class
A pseudo-class is used to define a special state of an element, which means style an element when a user moves the mouse over it or style an element when it gets focus etc.

Syntax for pseudo-class:

```
element:pseudo-class {
  property: value;
}
```
Now let’s take a look at some of the pseudo-classes.

- **Interactive States**

**`:hover`**

Selects an element when a user hovers their mouse pointer over it.

For example:

```
<button>Hover over me!</button>
```
CSS:

```
button:hover {
  background-color: black;
  color: #fff;
}
```
**`:active`**

Selects an element when a user clicks on it.

For example:

```
<a href="/">Click me!</a>
```
CSS:

```
a:active {
  color: red;
}
```
**`:focus`**

Select an element that is in a focus state.

```
 <input type="text">
```
CSS:

```
input:focus {
  background-color: red;
}
```
**`:visited`**

Style links that have been visited.

```
<a href="/">Click me!</a>
```
CSS:

```
a:visited {
  color: purple;
}
```
- **Styling Form Elements**

**`:disabled`**

You can style disabled inputs differently using `:disabled` pseudo-class.
 
```
<input type="text" disabled />
```
CSS:

```
input:disabled {
  border-color: red;
}
```
**`:enabled`**

You can style enabled inputs differently using `:enabled` pseudo-class.

```
 <input type="text" />
```
CSS:

```
input:enabled {
  border-color: green;
}
```
**`:checked`**

You can style the inputs after being checked using `:checked` pseudo-class.

```
<input type="checkbox" />
<input type="radio" />
```
CSS:

```
input:checked {
  height: 30px;
  width: 30px;
}
```
- **Styling Child Elements**

**`:first-child` and `:last-child`**

You can style the first child element and last child element of a parent element using `:first-child` and `:last-child` pseudo-classes respectively.

For example:

```
<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
```
CSS:

```
ul li:first-child{
  color: purple;
  font-size: 20px;
}
ul li:last-child{
  color: indigo;
  font-size: 30px;
}
```
**`:nth-child()`**

`:nth-child()` allows the selection of specific child elements based on their positions.

For example:

```
 <div>
    <p>This is first paragraph.</p>
    <p>This is second paragraph.</p>
    <p>This is third paragraph.</p>
    <p>This is fourth paragraph.</p>
    <p>This is fifth paragraph.</p>
</div>
```
CSS:

```
/* This will change the color of p at second position. */
div p:nth-child(2) {
  color: red;
}
/* This will change the color of p at fourth position. */
div p:nth-child(4) {
  color: green;
}
/* This will change the color of every p at odd number position. */
div p:nth-child(odd) {
  color: yellow;
}
/* This will change the color of every p at even number position. */
div p:nth-child(even) {
  color: blue;
}
```
You can try all the above styles one by one.

**`:nth-of-type()`**

`:nth-of-type()` narrows down the selection to a specific element type.

For example:

```
 <div>
    <p>This is first paragraph.</p>
    <p>This is second paragraph.</p>
    <p>This is third paragraph.</p>
    <p>This is fourth paragraph.</p>
    <p>This is fifth paragraph.</p>
</div>
```
CSS:

```
/* This will change the color of p at multiple of 2 positions. For example: 2, 4, 6... */
div p:nth-of-type(2n) {
  color: red;
}
/* This will change the color of p at multiple of 5 position. For example: 5, 10, 15... */
div p:nth-of-type(5n) {
  color: green;
}
```
**`:not()`**

`:not()` pseudo-class is used for excluding specific elements from being styled.

For example:

```
<div>
   <p>This is first paragraph.</p>
   <p>This is second paragraph.</p>
   <p class="third">This is third paragraph.</p>
   <p>This is fourth paragraph.</p>
</div>
```
CSS:

```
div p:not(.third) {
  color: red;
}
```
This will change the color of all `<p>` elements excluding the `<p>` element which has a class named `third`.

## Pseudo-Elements
A pseudo-element is used to apply styles to specified parts of an element. For example, style the first letter, or first line of an element, and insert content before, or after, the content of an element.

Syntax:

```
element::pseudo-element {
  property: value;
}
```
- **`::before`**

This is used to insert content before the selected element’s content.

```
<blockquote>This is a quote.</blockquote>
```
You can insert the `"` sign before the text using `:before`.

```
blockquote::before {
  content: '"';
}
```
- **`::after`**

This is used to insert content after the selected element’s content.

```
<blockquote>This is a quote.</blockquote>
```
You can insert the `"` sign after the text using `:after`.

```
blockquote::after {
  content: '"';
}
```
- **`::first-line`**

This is used to change the style of the first line of the text.

```
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis, dolorum
  similique, aliquid repellat beatae vero aliquam quis magnam, laboriosam
  cum eligendi quo harum reiciendis at fugit soluta quos nisi suscipit!
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis, dolorum
  similique, aliquid repellat beatae vero aliquam quis magnam, laboriosam
  cum eligendi quo harum reiciendis at fugit soluta quos nisi suscipit!
</p>
```
CSS:

```
p::first-line{
  color: red;
}
```
- **`::first-letter`**

This is used to change the style of the first letter of the text.

```
<p>This is a paragraph.</p>
```
CSS:

```
p::first-letter{
  color: red;
}
```
- **`::marker`**

This is used to change the style of the marker of the list item.

```
<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
```
CSS:

```
::marker {
  color: green;
}
```
- **`::selection`**

This is used to change the style of the selected text.

```
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis, dolorum
  similique, aliquid repellat beatae vero aliquam quis magnam, laboriosam
  cum eligendi quo harum reiciendis at fugit soluta quos nisi suscipit!
</p>
```
CSS:

```
::selection {
  color: white;
  background-color: purple;
}
```

## Attribute Selectors
Attributes of HTML elements provide additional information about the HTML element. You can style the elements by targeting them using their attributes.

- **[attr]**

Selects the elements with their attributes.

Example:

```
<input type="text" />
<input type="email" name="email" id="email" required />
```
CSS:

```
input[required] {
  border-color: blue;
}
```
- **[attr=value]**

Selects the elements with their attribute name and attribute value.

Example 1:

```
<input type="text" />
<input type="email" name="email" id="email" />
```
CSS:

```
input[type="email"] {
  border: 1px solid blue;
}
```
This will change the style of the email type inputs.

Example 2:

```
<a href="/">Click me!</a>
<a href="/" target="_blank">Click me!</a>
```
CSS:

```
a[target="_blank"] {
  text-decoration: overline;
}
```
- **[attr~=value]**

Selects elements containing a whole word. For example:

```
<p>This is paragraph.</p>
<p class="special">This is paragraph.</p>
<p>This is paragraph.</p>
```
CSS:

```
p[class~="special"] {
  color: blue;
}
```
This will change the color of the `<p>` element containing special class name.

- **[attr*=value]**

Selects elements **containing** a substring of a word. For example:

```
<img src="logo.png" alt="logo" />
<img src="image.png" alt="picture" />
<img src="logo.png" alt="logo" />
```
CSS:

```
img[src*="logo"] {
  border: 2px solid red;
}
```
This will change the style of all the image element that contains “logo” in its `src` attribute value.

- **[attr$=value]**

Selects elements with an attribute value **ending** with a specific word. For example:

```
<img src="logo.png" alt="logo" />
<img src="image.png" alt="picture" />
<img src="logo.jpg" alt="logo" />
```
CSS:

```
img[src$=".png"] {
  border: 2px solid red;
}
```
This will change the style of all the image elements which have their `src` attribute value ending with “.png”.

- **[attr^=value]**

Selects elements with an attribute value `starting` with a specific word. For example:

```
<a href="www.example.com">Example</a>
<a href="https://example.com">Example</a>
```
CSS:

```
a[href^="https:"] {
  color: red;
}
```
This will change the style of all the `<a>` elements which have their `href` attribute value starting with “https:”.

## Grouping Selectors
You can group multiple selectors to apply the same style to them.

For example:

```
<h1>This is first heading.</h1>
<h2>This is second heading.</h2>
<h3>This is third heading.</h3>
<p>This is paragraph.</p>
```
CSS:

```
h1, h2, p{
  color: purple;
  font-style: italic;
}
```

## Conclusion
Throughout this blog post, we have learned about the CSS selectors to style our web page elements specifically, using different types of selectors.

We have categorized the selectors as basic selectors, combinators, pseudo-classes, pseudo-elements and attribute selectors.

By embracing these selectors, you can craft web pages that not only look visually appealing but also offer a seamless and enjoyable user experience.

Thanks for reading.

For more content like this [click here](https://shefali.dev/blog)!

Keep Coding!
<a href="https://www.buymeacoffee.com/devshefali" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>