5: Your First CSS Rule

Why is nothing changing? Oh, specificity. The first CSS bug is always "I wrote a rule and nothing happened."

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?

SelectorExampleSelects…
** {…}everything
elementp {…}all <p>
.class.card {…}class="card"
#id#hero {…}id="hero" (one)
descendantnav a {…}<a> inside <nav>
pseudo-classa: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

  1. Inheritance: Some props pass down (color, font-family). Most don't (margin, border).
  2. Cascade: Later rule wins if specificity ties.
  3. 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

Mira, writes & bikes

I like long sentences and short rides. California-based, coffee-powered.

Read more

/* 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; }
Exercise: Style your About Me:
  1. Link a style.css to your Module 1 page (<link rel="stylesheet" href="style.css">).
  2. Set color, background, font-family on body.
  3. Add a .highlight class and use it on one sentence.
  4. Add a:hover { color: … }. The hover should be obvious.
  5. Try to break specificity: add #test { color: red; } and see it beat .highlight.
Prev4: Containers Next6: The Box Model