Skip to main content

Command Palette

Search for a command to run...

Why CSS Selectors Exist (And Why We Need Them)

Published
2 min read

CSS is used to style webpages, but here’s the big question: how does CSS know what to style?
A webpage can have hundreds of elements like :- headings, paragraphs, buttons, images. CSS selectors are the answer to this problem. CSS selectors are simply ways to choose specific HTML elements so styles can be applied to them.

You can think of selectors as instructions that say, “Apply this style to these elements.”

Element Selector :-

The Best Guide to Understand Selectors in CSS [Updated]

An element selector targets all elements of a given type. If you select p, every paragraph on the page will be affected. This is the simplest form of selection. It’s like saying, “Style all paragraphs the same way.”

Element selectors are useful for setting default styles across a page, such as font or text color.

Class Selector :-

A class selector is used when you want to style some elements, but not all. Classes are reusable and flexible. You can apply the same class to many elements. Classes are written with a dot . notation . When you use a class, you are saying, “Style all elements that belong to this group.”

ID Selector :-

An ID selector is used to style one specific element. IDs must be unique, meaning they should not be repeated on a page. IDs are written with a hash # notation. When you use an ID selector, you are saying, “Style only this one element.”

Group Selectors :-

Sometimes you want to apply the same style to different elements. Instead of writing styles again and again, you can group selectors together. Group selectors let you say, “Apply this style to all of these elements at once.” This keeps your CSS clean and readable.

Descendant Selectors :-

Descendant selectors target elements inside other elements. This means styling depends on where the element is placed in the HTML structure.
For example, you can style only paragraphs that exist inside a specific section. This gives you more control without needing extra classes.

Basic Idea of Selector Priority :-

When multiple selectors target the same element, CSS needs to decide which style wins. This is called priority.

At a very high level, the order is simple:

  • Element selectors have the lowest priority

  • Class selectors have more priority

  • ID selectors have the highest priority

A Very Basic Example of how elements appear before and after styling

Before Styling :-

After Styling :-