Selectors
Learn how to target HTML elements in CSS using element names, classes, and IDs.
Learning Goals
The Core Concept
CSS selectors tell the browser which HTML elements should receive your styles. You can target elements directly by their tag name (like `p` or `h1`), target groups of elements using a class (written with a dot, like `.btn`), or target a single specific element using an ID (written with a hash, like `#header`). Class selectors are the most common because you can reuse them on many different elements.
Visual guide
Css concept flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
/* Element Selector */
p {
color: #334155;
}
/* Class Selector */
.highlight-box {
background-color: #fef08a;
border: 1px solid #eab308;
}
/* ID Selector */
#main-cta-button {
background-color: #2563eb;
color: white;
}Expected Output
All paragraph text is dark slate color Highlight boxes have yellow background CTA button is blue with white text
Style a Custom Alert Box
Hands-on practice task
The Challenge
Write the CSS selectors to style a warning box. Target all paragraphs to have a font size of 16px, target the alert class .warning-alert to have a red color, and target a button with ID #close-btn to be hidden.
Helpful Hints
- •Use p for the element.
- •Use .warning-alert for the class.
- •Use #close-btn for the ID.
Quick Knowledge Check
What is the difference between a class and an ID?
Can an HTML element have multiple classes?
Continue Learning
Next steps after this lesson
Write the CSS selectors to style a warning box. Target all paragraphs to have a font size of 16px, target the alert class .warning-alert to have a red color, and target a button with ID #close-btn to be hidden.
Ready to put your coding skills to the test?
Don't just read—write code! Use our free Try-Code Playground to experiment with real-time preview, or search utilities on our Developer Tools List.