Why Do We Need CSS Selectors?
CSS is used to make a website look good. But CSS first needs to know which HTML element to style.
That is why we use CSS selectors.
Selectors help CSS choose elements on a webpage.
Think of selectors like calling people by name:
- Calling "Everyone" → all people respond
- Calling "People in blue shirts" → only a group responds
- Calling "Rahul" → one person responds
CSS works the same way.
Element Selector
The element selector selects elements by their HTML tag name.
p {
color: blue;
}
This will change the color of all paragraphs.
Use element selectors when:
- You want to style all same elements
- You need simple and global styling
Class Selector
A class selector selects elements using a class name.
Class selectors start with a dot (.).
HTML:
<p class="note">This is important</p>
CSS:
.note {
color: red;
}
Class selectors are:
- Reusable
- Very common
- Flexible
You can use the same class on many elements.
ID Selector
An ID selector selects one unique element.
ID selectors start with a hash (#).
HTML:
<h1 id="title">Welcome</h1>
CSS:
#title {
color: green;
}
Rules for ID:
- Used only once
- Not reusable
Group Selector
Group selectors let you style many elements at once.
h1, h2, p {
font-family: Arial;
}
This saves time and keeps CSS clean.
Descendant Selector
A descendant selector selects elements inside another element.
div p {
color: purple;
}
This means:
- Select
<p> - Only if it is inside
<div>
Basic Selector Priority
Sometimes more than one selector styles the same element.
Who wins?
- ID selector (strongest)
- Class selector
- Element selector (weakest)
The stronger selector is applied.
Top comments (0)