🎨 CSS

Selectors

Lesson 2 of 5 ~7 min

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 */
p { color: gray; }

/* Class selector */
.highlight { background: yellow; }

/* ID selector */
#header { font-size: 24px; }

Combinators

Combinators define the relationship between selectors:

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.