CSS Selectors 101: Targeting Elements with Precision
CSS Selectors:
When people start learning CSS, they often focus on colors, fonts, and layouts. But before any of that matters, there’s a more basic question that CSS must answer first:
Which element should this style apply to?
That’s exactly why CSS selectors exist. Selectors are the way we choose elements on a webpage. Without selectors, CSS would have no idea where to apply styles, and every page would look the same.
Why CSS Selectors Are Needed
A webpage is made up of many HTML elements—headings, paragraphs, buttons, images, containers. CSS selectors act like instructions that tell the browser, “Apply this style to these elements, not all of them.”
Selectors as a Way to Choose Elements
At a high level, every CSS rule has two parts:
The selector – who the rule applies to
The styles – what changes should be applied
The selector is always written first. Everything else depends on it.
Element Selector
The element selector is the simplest form of selection. It targets all elements of a given type.
For example, if you want all paragraphs to look the same, you use the p selector.
p { color: blue; }
This tells the browser to apply the style to every <p> element on the page. Element selectors are useful for setting broad, default styles.
Class Selector
As pages grow, you often want to style some elements differently, not all of them. This is where class selectors come in.
A class selector targets elements with a specific class attribute.
.highlight {
background-color: yellow;
}
Classes are reusable. You can apply the same class to many elements across a page.
ID Selector
ID selectors are even more specific. An ID is meant to identify one unique element on a page
#main-title {
font-size: 32px;
}
IDs should not be reused. They are best for elements that appear only once, such as a main heading or a primary container.
Class vs ID (When to Use Which)

A good rule of thumb:
Use classes for reusable styles
Use IDs for unique elements
Group Selectors
Sometimes you want to apply the same style to multiple selectors. Instead of repeating code, CSS allows grouping.
h1, h2, h3 { font-family: Arial; }
Basic Selector Priority
Sometimes multiple selectors target the same element. When that happens, the browser needs a way to decide which rule wins.
At a very high level:
ID selectors have the highest priority
Class selectors are next
Element selectors have the lowest priority
This is known as specificity
Before and After: Why Selectors Matter
Without selectors, every paragraph, heading, and button would look the same. With selectors, you can control layout and appearance precisely.
Selectors are the foundation of CSS. Colors, spacing, animations, and layouts all depend on selecting the right elements first.