Forem

Harshita Kanal
Harshita Kanal

Posted on

2 2

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.

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay