CSS Selectors
Element, class, ID, and attribute selectors — the different ways to target the elements you want to style.
2 min de lecture
A selector is the part of a CSS rule that decides which elements a declaration block applies to. Picking the right kind of selector is one of the most important skills in writing maintainable CSS.
Element (type) selectors
p {
line-height: 1.6;
}Targets every element of that tag name on the page. Good for broad, foundational styles — but too broad for anything you want to style differently in different places.
Class selectors
.card {
padding: 16px;
border-radius: 8px;
}<div class="card">...</div>A class selector starts with a dot and matches any element with that class in its class attribute. Classes are reusable (many elements can share one) and combinable (one element can have several classes), which makes them the workhorse selector for almost all component styling.
ID selectors
#site-header {
position: sticky;
top: 0;
}<header id="site-header">...</header>An ID selector starts with # and matches the one element with that id. IDs must be unique per page, which makes them suited to one-off elements like a page header — but they carry very high specificity (covered in the next lesson), which makes them hard to override later. Most style guides recommend classes over IDs for styling, reserving IDs for anchors and JavaScript hooks.
Attribute selectors
input[type="email"] {
border-color: #94a3b8;
}
a[target="_blank"] {
text-decoration: underline dotted;
}
a[href^="https://"] {
color: green;
}Attribute selectors match elements based on an attribute's presence or value. [type="email"] matches exactly, [href^="https://"] matches attributes that start with that value ($= for "ends with", *= for "contains anywhere"). These are especially useful for styling form inputs by type without adding a class to each one.
The universal selector
* {
box-sizing: border-box;
}* matches every element on the page. It's rarely used for visual styling (too broad), but it shows up constantly in one specific pattern — resetting box-sizing globally, which you'll see again in the box model lesson.
Choosing between them
A practical rule of thumb: use element selectors for base/default styles, classes for anything reusable or component-specific, attribute selectors for form inputs and link variants, and IDs sparingly — mainly for page landmarks and #hash navigation targets rather than for visual styling.