Rules and Selectors

What this is. A CSS rule has two halves. The selector says which elements this applies to. The declaration block says what to do to them.

`

selector {

property: value;

}

`

That is the entire syntax. Everything else in CSS is vocabulary.

The selectors that do almost all the work:

p selects every paragraph, by element type.

.card selects everything carrying class="card".

#hero selects the one element with id="hero".

nav a selects anchors anywhere inside a nav, called a descendant selector.

nav > a selects anchors that are direct children of nav only.

✦ Why classes rather than ids

An id must be unique on the page, so a rule written for one can never be reused. A class can appear on as many elements as you like. Style with classes almost always, and save ids for link targets and for labeling form fields.

LIVE PREVIEW
loading editor…

Your turn → Change the last rule's selector from `nav a` to `nav > a`. The nested link gets its underline back, because it is a grandchild rather than a direct child.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: The Cascade, Inheritance, and Specificity →
← Back