Selectors and syntax
โ Report an issue with this lessonCSS rules follow one pattern: a selector, then declarations in curly braces.
h1 {
color: navy;
font-size: 32px;
}
Selectors target elements a few ways:
p { } /* every <p> */
.card { } /* class="card" */
#main-nav { } /* id="main-nav" */
p.intro { } /* a <p> with class="intro" */
nav a { } /* any <a> inside <nav> */
Classes are what you'll use constantly -- an element can have several,
separated by spaces: <div class="card featured">. IDs
should stay rare, reserved for one-of-a-kind elements like a page's main
nav.
Where CSS lives
You've seen CSS inside a <style> block, but in real
projects it almost always lives in a separate .css file,
linked from the <head>:
<link rel="stylesheet" href="styles.css">
This keeps structure (HTML) and presentation (CSS) separate, and lets one
stylesheet style every page on a site. You'll also sometimes see an
style attribute directly on an element --
<p style="color: red;"> -- called an inline style. It
works, but avoid it in real projects: it can't be reused, and it silently
overrides your stylesheet in ways that get confusing fast.
Combining and grouping selectors
h1, h2, h3 {
font-family: "Georgia", serif;
}
.card.featured { } /* an element with BOTH classes, no space between them */
.card > p { } /* a <p> that is a DIRECT child of .card */
.card p { } /* a <p> ANYWHERE inside .card, any depth */
The comma groups unrelated selectors that should share the same rule. The
space vs. > distinction trips people up constantly: a
descendant selector (space) matches at any nesting depth, while a child
selector (>) matches only one level down.
Specificity, briefly
When two rules target the same element with conflicting values, the
browser picks a winner using specificity, roughly in this order of
increasing power: element selectors (p) < class selectors
(.intro) < ID selectors (#main). An ID
selector will beat a class selector even if the class rule appears later in
the file:
#main { color: blue; } /* wins */
.intro { color: red; } /* loses, even though it's written after */
This is exactly why IDs should stay rare for styling -- a rule written
against an ID is hard to override later without reaching for another ID or
!important, both of which make a stylesheet harder to maintain
over time. When in doubt, style with classes.
Try it yourself
9 more lessons โ including Project: style your portfolio page โ plus a certificate are waiting.
Unlock the full course โ $29.99