CSS Selectors
CSS Selectors
CSS selectors are used to target HTML elements and apply styles to them. A selector can target elements by name, by class, by id, or by how they appear in the HTML structure.
In general, selectors help you answer a simple question: “Which elements do I want to style?”
Element Selector
The element selector selects all elements with the specified tag name.
p {
color: #333;
line-height: 1.6;
}
The rule above styles all <p> elements on the page.
ID Selector
The id selector selects a single element with a specific id. An id should be unique within a page.
#header {
background: #f5f5f5;
padding: 16px;
}
This rule styles the element that has id="header".
Class Selector
The class selector selects all elements with a specific class. Classes are reusable and are the most common way to apply styles to many elements.
.card {
border: 1px solid #ddd;
border-radius: 10px;
padding: 16px;
}
This rule styles all elements that have class="card".
Universal Selector
The universal selector (*) selects all elements. Use it carefully because it can affect performance and override expectations.
* {
box-sizing: border-box;
}
Selector Examples (HTML + CSS)
Here is a small HTML snippet and some selectors that target it:
<div id="header" class="card"> <h2 class="title">Welcome</h2> <p>This is a paragraph.</p> </div>
#header {
background: #f8fbff;
}
.card {
border: 1px solid #cfe3ff;
}
.title {
color: #1f4bd8;
}
Grouping Selectors
If multiple selectors need the same styles, you can group them by separating them with commas. This keeps your CSS clean and easier to maintain.
h1, h2, h3 {
font-family: Arial, sans-serif;
letter-spacing: 0.2px;
}
The rule above applies to all h1, h2, and h3 elements.
Grouping vs Repeating
These two examples produce the same result, but grouping is shorter and easier to update:
/* Repeating */
h1 { color: #222; }
h2 { color: #222; }
h3 { color: #222; }
/* Grouping */
h1, h2, h3 { color: #222; }
Code Challenge
Goal: Style the elements below using selectors. Use an id selector for the main box, and a class selector for the labels.
HTML:
<div id="profile"> <h3 class="label">Name</h3> <p>Ozan</p> <h3 class="label">Role</h3> <p>Developer</p> </div>
Task:
- Give
#profilea light background and some padding - Make
.labeltext a bit darker and slightly spaced - Increase paragraph line height for readability
Try a Solution:
#profile {
background: #f7f7f7;
padding: 16px;
border-radius: 10px;
}
.label {
color: #222;
margin-bottom: 4px;
letter-spacing: 0.3px;
}
p {
line-height: 1.6;
margin-top: 0;
}
What’s Next?
Next, you will learn more ways to target elements, including combinators and pseudo-classes for more precise styling.