Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Published
2 min read

We know that CSS(Cascading style sheet) is used to design the web pages. The selectors in CSS helps to select the specific parts of the web pages to style, design or color.

Why we need selectors

Selector are used to select a part of the webpage (eg an element) and give a specific design for it. These are helpful since we can design the web page dynamically.


The Element Selector

The element selector is used to select all the instances of a specific element.

p {
    color : blue;
}

Every single paragraph in the page turns blue.

The class selector

A class is a reusable identifier used to apply the same styles to multiple elements across a page. The class selector is used to select all the classes with the same name.

<p class="highlight"> text 1 </p>
<p class="highlight"> text 2 </p>
<p class="highlight"> text 3 </p>
.highlight { background-color: yellow; }

The ID selector

An ID is a unique identifier used to target a single, specific element on a page. The ID selector is used to select an element with a specific ID.

<div id="main-header">Welcome</div>
#main-header {
    color : brown;
}

Group Selectors (The "Shortcut")

If you want the same style for different types of elements, don't repeat yourself! Separate the names with a comma.

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

  • Result: All three types of elements will now use Arial.

Descendant Selectors (The "Relationship" approach)

This targets an element only if it is inside another specific element. You do this by putting a space between the selectors.

footer p { color: gray; }
  • Result: Only paragraphs inside a <footer> turn gray. Other paragraphs stay the default color.

Selector Priority (Who Wins?)

What happens if a paragraph has a class that says it should be blue, but an ID that says it should be red? CSS has a "Specifity" rule (a hierarchy of power):

  1. ID (#) - The Heavyweight Champion (Strongest)

  2. Class (.) - The Middleweight

  3. Element (p, div) - The Lightweight (Weakest)

Quick Tip: If styles aren't showing up, it's often because a "stronger" selector is over-ruling a "weaker" one!