🎨 CSS
Selectors
CSS selectors are patterns used to target and select HTML elements for styling. The right selector lets you apply styles precisely where you want them.
Basic selectors
- → Element selector — targets elements by tag name:
p,h1,div - → Class selector — targets elements with a specific class:
.classname - → ID selector — targets a single element with a specific ID:
#idname
/* Element selector */
p { color: gray; }
/* Class selector */
.highlight { background: yellow; }
/* ID selector */
#header { font-size: 24px; }
Combinators
Combinators define the relationship between selectors:
- → Descendant (
div p) — matchespinside adivat any depth - → Child (
div > p) — matchespthat is a direct child ofdiv - → Adjacent sibling (
h1 + p) — matchespimmediately afterh1
Pseudo-classes
Pseudo-classes let you style elements based on their state:
a:hover { color: red; } /* When mouse is over */
input:focus { border: 2px solid blue; } /* When input is active */
li:first-child { font-weight: bold; } /* First item in list */
Try it yourself
Editor
CSS
Output
Try it
Edit the CSS to style the heading with an element selector, the box with a class selector, and the emphasized text with an ID selector.
Quiz
Which symbol is used for a class selector?
Challenge
In the editor above, add a class selector to style one element and an ID selector to style a different element. Experiment with pseudo-classes like :hover.