Type, class, ID and universal selectors
Definition and purpose
A type selector matches an element name, a class selector matches a token in its class attribute, an ID selector matches its id, and the universal selector matches any element. Use classes for reusable styling, IDs for unique document anchors, and types for broad defaults.
Four selector types
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> * { font-family: sans-serif; } p { color: navy; } .card { background-color: white; } #featured { color: green; } </style> </head> <body> <p id="a" class="card note">First</p> <p id="b">Second</p> <h2 id="featured">Feature</h2> </body></html>The class targets one paragraph, the type targets both, and the ID targets the heading.
Syntax and mental model
The syntax is p, .card, #featured, and *. An element can have multiple space-separated class tokens; .card matches even when another class is present. HTML IDs must be unique in a document, although duplicate IDs can still match CSS. The universal selector does not select text nodes or pseudo-elements by itself.
Reusable class
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>.note { color: green; }</style> </head> <body> <p id="a" class="note">One</p> <h2 id="b" class="note special">Two</h2> <p id="c">Three</p> </body></html>Both elements with the note token match regardless of tag name.
Common mistakes
Do not write card when you mean .card: the first targets a tag named card. Avoid repeating an ID to apply a shared style; use a class.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: First styled profile. Next lesson: Selector lists and compound selectors.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type, class, ID and universal selectors — knowledge check
Five questions on type, class, id and universal selectors.
Which selector matches class="card selected"?
What does #featured match?
What does * select by itself?
How should five reusable cards share a style?
Which selector targets all p elements?