CSS selectors are patterns used to 'select' the HTML elements you want to style. They are the target of your CSS rules, telling the browser which parts of the page to apply the formatting to.
*)The universal selector targets every single element on the HTML page. It is frequently used for resets (like removing default margins and padding).
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
The element selector selects elements based on their HTML tag name (like h1, p, div, etc.).
p {
color: #333;
line-height: 1.6;
}
h1 {
color: #2e7d52;
}
.class)The class selector targets elements with a specific class attribute. Unlike IDs, classes can be reused on multiple elements within the same page.
.highlight-text {
color: #2e7d52;
font-weight: bold;
}
#id)The ID selector uses the id attribute of an HTML element to select a **single, unique** element. An ID should only be used once per page.
#unique-element {
background-color: #e8f5e9;
padding: 5px;
border-radius: 4px;
}
If multiple elements share the same style, you can group their selectors by separating them with a **comma** to keep your code clean.
/* Styles multiple heading levels at once */
h1, h2, h3 {
text-align: center;
color: #2e7d52;
}
. or # prefix. Writing highlight-text { ... } instead of .highlight-text { ... } targets a (probably nonexistent) element named highlight-text, not the class.
* carelessly. A universal selector reset is common, but stacking more * rules later in the stylesheet can unexpectedly override styles on third-party widgets or embedded components.
Combining an element selector with a class selector — a realistic pairing you'll use constantly:
<nav>
<a class="nav-link" href="#">Home</a>
<a class="nav-link" href="#">About</a>
</nav>
<style>
nav a.nav-link {
text-decoration: none;
color: #2e7d52;
margin-right: 12px;
}
nav a.nav-link:hover {
text-decoration: underline;
}
</style>
Rendered result:
Q: What's the difference between a class and an ID selector?
A: A class (.name) can be reused on many elements; an ID (#name) should appear once per page. Classes are almost always the better default for styling.
Q: Can I combine a tag and a class in one selector, like p.intro?
A: Yes — p.intro only matches <p> elements that also have class="intro", which is more specific than either selector alone.
Q: Which has higher specificity, a class or an element selector?
A: A class always beats an element selector, and an ID beats a class. See the MDN specificity guide for the full calculation rules.