Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

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

Why CSS selectors are needed

You wrote HTML.

If you're new to HTML, you can first understand how tags and elements work.
HTML Tags & Elements blog

Now you want to style it.

But how does CSS know which element to style?

That’s where selectors come in.

Selectors are used to choose HTML elements so CSS can apply styles to them.


Think of selectors like addressing people

Imagine a classroom.

  • You can call everyone → general

  • You can call a group → specific

  • You can call one person → very specific

CSS works the same way.


Element selector

Targets all elements of a type.

p {
  color: blue;
}

👉 This will style all <p> elements

This works because HTML is structured in a parent-child hierarchy.

HTML Tags & Elements blog


Class selector

Targets elements with a specific class.

<p class="text">Hello</p>
.text {
  color: green;
}

👉 This styles all elements with class="text"


ID selector

Targets a single unique element.

<p id="main">Hello</p>
#main {
  color: red;
}

👉 IDs are meant to be unique


Group selectors

Apply same style to multiple elements.

h1, p {
  color: purple;
}

👉 Saves repetition


Descendant selectors

Target elements inside another element.

<div>
  <p>Hello</p>
</div>
div p {
  color: orange;
}

👉 This selects <p> inside <div>


Basic selector priority (very simple)

Not all selectors are equal.

Some are more specific.

Priority (high → low):

ID > Class > Element

👉 ID wins over class 👉 Class wins over element


Quick comparison

Selector Example Use case
Element p style all elements
Class .text reuse styles
ID #main unique element

Before vs After

HTML

<p class="text">Hello</p>
<p>World</p>

CSS

.text {
  color: blue;
}

👉 Only first paragraph changes


Key Insight

Selectors are the foundation of CSS.

If you don’t understand selectors, you can’t control styling properly.


Try This

Write this HTML:

<div>
  <p class="text">Hello</p>
  <p>World</p>
</div>

Now try:

p {
  color: red;
}

Then try:

.text {
  color: green;
}

See the difference.


Final Thought

CSS is not about colors and design.

It starts with targeting the right element.