| Selector | Syntax | Selects |
|---|---|---|
| Universal | * { } | Every element |
| Element (type) | p { } | All <p> elements |
| Class | .note { } | Elements with class='note' (reusable) |
| ID | #header { } | The one element with id='header' (unique per page) |
| Group | h1, h2, p { } | Several selectors sharing one rule |
HTML
<h1 id='title'>Shop</h1>
<p class='note'>Free delivery</p>
<p class='note urgent'>Ends today</p> <!-- an element can have several classes -->CSS
* { margin: 0; padding: 0; }
#title { color: navy; }
.note { background: #fff3cd; padding: 8px; }
.note.urgent { color: red; } /* both classes on the same element, no space */
h1, h2, h3 { font-family: Arial, sans-serif; }Combinators (relationships between elements)
| Selector | Meaning |
|---|---|
div p | Any p inside a div (descendant) |
div > p | p that is a direct child of div |
h1 + p | The p immediately after an h1 |
h1 ~ p | All p siblings after an h1 |
Attribute selectors: input[type='text'] { }, a[href^='https'] { } (starts with).
Specificity (highest wins): inline style, then ID, then class/attribute/pseudo-class, then element. Example: #title beats .note beats p. Avoid !important unless essential.
Nesting CSS
Modern CSS lets you write a rule inside another so related styles stay together and you do not repeat the parent selector. It is supported in current browsers.
CSS
.card {
padding: 16px;
border: 1px solid #ccc;
h2 { color: navy; } /* same as .card h2 */
p { line-height: 1.6; } /* same as .card p */
&:hover { box-shadow: 0 4px 10px rgba(0,0,0,.2); } /* & means .card itself */
&.featured { border-color: gold; } /* .card.featured */
}Card title
The nested rules style this heading and paragraph. Hover the card.
Featured card
This one also has the class featured.
Sass and Less (tools that compile to CSS) offered nesting for years; native CSS nesting now does the same job without tools.