There are three ways to add CSS:
<!-- 1. External (preferred) -->
<link rel="stylesheet" href="style.css">
<!-- 2. Internal -->
<style>
p { color: tomato; }
</style>
<!-- 3. Inline (avoid, this is a specificity nightmare) -->
<p style="color: tomato">hi</p>
Why external wins: It's one file that affects many pages. Change
style.css once, and every page updates. Keep <style> for demos, ditch style="" except for emails.Selectors: who gets the style?
| Selector | Example | Selects… |
|---|---|---|
* | * {…} | everything |
| element | p {…} | all <p> |
.class | .card {…} | class="card" |
#id | #hero {…} | id="hero" (one) |
| descendant | nav a {…} | <a> inside <nav> |
| pseudo-class | a:hover {…} | on hover |
Hover this link, a:hover turns orange
.highlight The class selector paints me yellow
I have both .highlight and #demo-unique. Which wins?
.highlight { background: #fff7cc; } /* class */
#demo-unique { background: #e0f0ff; } /* id wins over class */
a:hover { color: orange; } /* pseudo-class */
Cascade, inheritance, specificity
The rules in order
- Inheritance: Some props pass down (
color,font-family). Most don't (margin,border). - Cascade: Later rule wins if specificity ties.
- Specificity:
ID > class > element.
I'm inheriting blue from parent.
But my border is mine, not inherited.
/* specificity: 0,1,0 vs 1,0,0, id wins */
.card { color: black; } /* 0,1,0 */
#hero { color: blue; } /* 1,0,0 wins */
/* same specificity, last wins */
p { color: red; }
p { color: green; } /* green wins */
Gotcha: Don't reach for
!important. It wins over everything and makes later fixes painful. Fix specificity by using a more specific selector or moving the rule later.Instant gratification properties
color + background: text & fill
font-family: try Georgia vs. monospace
font-family: Georgia + big font-size
body {
color: #111;
background: #fff;
font-family: Georgia, serif;
}
h1 {
color: #0b57d0;
font-family: -apple-system, Helvetica, sans-serif;
}
Live demo: style "About Me" in 10 lines
/* lines that make a page feel designed */
body { color:#111; background:#fff; font-family: Georgia, serif; line-height:1.6; }
h2 { font-family:-apple-system, sans-serif; color:#0b57d0; }
a { color:#0b57d0; } a:hover { color: tomato; }
.highlight { background:#fff7cc; padding:0 4px; }
- Link a
style.cssto your Module 1 page (<link rel="stylesheet" href="style.css">). - Set
color,background,font-familyonbody. - Add a
.highlightclass and use it on one sentence. - Add
a:hover { color: … }. The hover should be obvious. - Try to break specificity: add
#test { color: red; }and see it beat.highlight.