CSS Selectors 101: Targeting Elements with Precision
Aspiring Full-Stack Developer
If you are learning CSS, one of the most important topics you’ll come across is selectors. Selectors decide which HTML element should get styled. Without selectors, CSS would not know where to apply colors, fonts, spacing, or layouts.

Tag (Element) Selector
The tag selector is the most basic form of selector. Here, you directly select an HTML tag and apply styles to all elements of that type.
For example, if you want to style all buttons on a page, you can directly target the button tag.
<button>Submit</button>
<button>Cancel</button>
button {
background-color: red;
color: white;
}
Every <button> on the page will now have the same style. This is useful when you want a common design for similar elements like buttons, paragraphs, headings, or spans.
Class Selector
Sometimes, you don’t want to style every element of a particular tag. You only want to style some specific ones. That’s where class selectors come in.
Classes are reusable and can be applied to multiple elements.
<p class="highlight">This is the first paragraph</p>
<p class="highlight">This is the second paragraph</p>
<p>This is a normal paragraph</p>
.highlight {
background-color: red;
color: white;
}
Both paragraphs with the highlight class get styled, while the third one remains unchanged.
This is the biggest advantage of classes »reuse and flexibility.
ID Selector
An ID selector is used when you want to style only one unique element on the page. IDs should never be reused.
<a id="new_link" href="javascript:void(0)">This is a new link</a>
#new_link {
font-size: 30px;
text-transform: uppercase;
color: blue;
}
Here, the # symbol is used to target the ID.
Unlike classes, an ID is meant for one element only, which makes it useful for unique components like headers, main sections, or special links.
Parent and Child Selector
CSS also allows you to style elements based on their relationship. This is extremely powerful when working with layouts.
Let’s say we have a parent div and a child div inside it.
<div class="parent">
<div class="child">I am the child</div>
</div>
Now let’s style the parent first.
.parent {
width: 200px;
height: 100px;
background-color: black;
}
If you want to style the child only when it is inside this parent, you can do this:
.parent .child {
color: red;}
This selector means:
» Select .child only if it exists inside .parent.
This approach is very useful when building structured layouts and avoiding unnecessary styling conflicts.