CSS Tutorial
CSS Selectors
Selectors are how you tell CSS which HTML elements to style. Mastering selectors is the key to controlling exactly what changes on your page.
What is a selector?
A CSS selector is the part of a rule that decides which elements the styling applies to. Choose the wrong selector and nothing changes, or the wrong thing changes. There are several types, and each targets elements in a different way.
Element selector
The element (or type) selector matches all elements of a given tag name. For example, "p" selects every paragraph on the page.
p {
color: green;
}Id selector
The id selector targets one unique element with a specific id. In CSS you write a hash (#) followed by the id name. An id should be used only once per page.
#intro {
font-weight: bold;
}Class selector
The class selector targets all elements with a given class. In CSS you write a dot (.) followed by the class name. Unlike ids, a class can be reused on many elements, which makes classes the most popular selector.
.highlight {
background-color: yellow;
}Try selectors in action
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: #333;
}
#main-title {
color: navy;
text-align: center;
}
.note {
background-color: #fff3cd;
padding: 8px;
border-left: 4px solid #ffb400;
}
</style>
</head>
<body>
<h1 id="main-title">CSS Selectors</h1>
<p>This is a normal paragraph.</p>
<p class="note">This paragraph uses the .note class.</p>
</body>
</html>Universal and grouping selectors
The universal selector (*) selects every element on the page. The grouping selector lets you apply the same styles to several selectors at once by separating them with commas.
* {
margin: 0;
}
h1, h2, h3 {
color: teal;
}Common selectors summary
| Selector | Syntax | Selects |
|---|---|---|
| Element | p | All <p> elements |
| Id | #intro | The element with id="intro" |
| Class | .box | All elements with class="box" |
| Universal | * | Every element |
| Grouping | h1, h2 | All <h1> and <h2> elements |
Prefer classes over ids for styling. Classes are reusable, and it keeps your CSS flexible when your page grows.
Key points
- Selectors decide which elements get styled.
- Element selectors use the tag name (p, h1).
- Id selectors use # and should be unique.
- Class selectors use . and can be reused.
- * selects everything; commas group selectors.
