Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Published
3 min read
CSS Selectors 101: Targeting Elements with Precision

Why CSS selectors are needed

Main work of CSS is: apply styles to HTML elements.
But before styling anything, CSS must answer one question: Like how will it know where and on which element to apply those styles??

That’s exactly what CSS selectors are used for.
Selectors are ways to choose elements from the HTML.

Its used to select and target HTML elements on a web page to apply specific styling rules to them. They are the core of CSS and allow developers to precisely control the look and feel of a website./
Imagine a classroom.

  • If you say “Everyone wear a cap” → element selector

  • If you say “Only students in the red team” → class selector

  • If you say “Only Rahul” → ID selector

Styles written in universal selector will apply to all HTML elements.

Element selector

The element selector selects elements by their tag name.

Example:

p {
  color: blue;
}

This means: “Style all <p> elements.”

Before:

<p>First Paragraph of text.</p>
<p>Second Paragraph of text.</p>
<spna>And a span of text.</span>

After:

  • Both paragraphs turn blue

Class selector

A class selector selects elements using a class name.

<p class="highlight">Important text</p>
<p>Normal text</p>
.highlight {
  color: red;
}

Only the element with class="highlight" is styled and it’s text color is changed to red.

  • Classes can be reused

  • Multiple elements can share the same class

ID selector

An ID selector targets one unique element.

<h1 id="main-title">Welcome</h1>
#main-title {
  font-size: 32px;
}
  • IDs should be unique

  • One ID = one element

Group selectors

Sometimes, you want to apply the same style to multiple selectors.

h1, h2, p {
  font-family: Arial;
}

This means: Apply this style to all h1, h2, and p elements.

Group selectors help:

  • Reduce repetition

  • Keep CSS clean

Descendant selectors

A descendant selector targets elements inside another element.

div p {
  color: green;
}
<div>
  <p>This turns green</p>
</div>
<p>This stays normal</p>

Only the <p> inside <div> is affected and css styles is applied to them.

Analogy: Only students inside this classroom.

Basic selector priority

Sometimes, multiple selectors target the same element.
CSS then decides which rule wins or can say which rule to apply. This happens by of their priority.

ID selector (Highest, means whatever written in this have highest priority, so only it will apply at the end.)
Class selector(Less than ID but greater then Element)
Element selector (weakest)

p { color: blue; }
.text { color: red; }
#para { color: green; }

Final color → green (ID wins).

Thank you for reading!
You can watch this 100s video for css overview!

CSS Selectors Explained: Element, Class, ID & Basic Priority for Begin