CSS Selectors: A Primer

harshitakanal

Harshita Kanal

Posted on November 15, 2020

CSS Selectors: A Primer

CSS Selectors

CSS or Cascading Style Sheets is used to style HTML elements.
Element styling typically involves:

  • Selecting the element
  • Applying the specific styles.

A Typical example of an HTML element could be:

<h1> hello </h1>
Enter fullscreen mode Exit fullscreen mode

Here the h1 is an HTML element.
Now we need to select this specific element in our CSS file, this would be done by using
a selector.

A simple selector

The simplest CSS selector could be, an Element selector.

h1{
color: red;
}
Enter fullscreen mode Exit fullscreen mode

The above is an example of an element selector, it would do exactly what its name says, select all specified elements on the page and apply the said styles,in this case it would select all h1 elements and make it red.

Let's get more specific!

Element selectors are good, but we may not need to apply the same styles to all instances of the selected element on the page,
i.e. All h1 elements may not be red!

There could be situations when only some h1 elements need to be red, here we use more specific Selectors.

Class selectors

A class selector looks like this:

.myColoredTag{
color: red;
}
Enter fullscreen mode Exit fullscreen mode

We apply a class to an HTML element as:

<h1 class="myColoredTag"> hello </h1>
Enter fullscreen mode Exit fullscreen mode

In this case, the same set of styles would be applied to all the elements having the same class name.
This could be considered as one of the most used tags, as it can later help you to use various CSS frameworks, example: bootstrap and apply framework specific styles.

ID Selectors

An ID selector looks like this:

#myColoredTag{
color: red;
}
Enter fullscreen mode Exit fullscreen mode

We can apply an ID to an HTML element as:

<h1 id="myColoredTag"> hello </h1>

Enter fullscreen mode Exit fullscreen mode

Each page can have only one element with same id, an id is thus unique.

💖 💪 🙅 🚩
harshitakanal
Harshita Kanal

Posted on November 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Understanding CSS Specificity
css Understanding CSS Specificity

December 22, 2021

CSS Box Model
css CSS Box Model

July 15, 2021

CSS Selectors: A Primer
css CSS Selectors: A Primer

November 15, 2020

Nenhuma DIV escapa dessa!
css Nenhuma DIV escapa dessa!

April 11, 2020