Selectors are the bridge between CSS and HTML: they tell the browser "which elements this rule should apply to". This section introduces the four most basic ways to select — universal, type, class, and ID — which are the building blocks of almost every complex selector.
The Universal Selector *
* matches any element in the document, often used to clear the browser's default margins and padding.
TipThe performance cost of the universal selector is nearly negligible in modern browsers, but it is still advisable to use it only in a few "reset" scenarios to avoid masking where styles really come from.
Type Selectors
Using an HTML tag name directly as the selector matches every element of that type on the page.
p {
line-height: 1.6;
}
ul {
list-style: none;
}
Class Selectors
Starting with a period ., it matches every element whose class attribute contains that name. An element can have several classes; this is the most common selection method in component-based development.
Starting with #, it matches the element with the corresponding id attribute. Because an id is theoretically unique on a page, ID selectors have far higher specificity than class selectors (see 2.2 Combinators and Specificity). In component-based projects, it is usually recommended to style with class selectors only and leave id for anchor jumps and JavaScript hooks.
#main-nav {
position: sticky;
top: 0;
}
Grouping Selectors
Joining several selectors with commas shares one set of style declarations across them, effectively reducing duplicated code.