CSS Selectors
Selectors are used to choose elements in HTML and apply styles to them.
You may have many elements, but sometimes you want to style only specific ones.
Element Selector (by tag)
Selects all elements of the same type.
p {
color: tomato;
}
All paragraphs will become red.
Example:
h1 { color: red; }
a { color: blue; }
ID Selector (#id)
Selects one unique element.
#title {
color: orange;
}
<h1 id="title">Hello</h1>
ID must be unique and is rarely used for styling.
Class Selector (.class)
The most important selector in real projects.
.title {
color: skyblue;
}
<h2 class="title">Hello</h2>
More examples:
.text { color: brown; }
.link { color: tomato; }
Classes are reusable and flexible.
Descendant Selector (X Y)
Selects elements inside another element (any depth).
ul a {
color: red;
}
.social-links a {
color: blue;
}
Child Selector (X > Y)
Selects only direct children.
.menu > li {
color: red;
}
Pseudo-classes (states)
Used for user interaction.
:hover
a:hover {
color: orange;
}
:active
a:active {
color: red;
}
:focus
input:focus {
border: 2px solid blue;
}
Combined:
a:hover,
a:focus {
color: orange;
}
Full Example
.page-nav .link {
color: #00bcd4;
}
.page-nav .link:hover,
.page-nav .link:focus {
color: #18ffff;
}
.page-nav .link:active {
color: #212121;
}
Summary
- Element selector → all elements
- ID → one element
- Class → best and reusable
- Descendant → any depth
- Child → direct only
- :hover → mouse
- :active → click
- :focus → keyboard