CSS: getting started

How a stylesheet attaches to HTML, how rules are read, and the cascade that decides which declaration wins.

Three ways to attach CSS

MethodHowWhen
External file<link rel='stylesheet' href='app.css'>Default choice β€” cacheable, reusable
Internal block<style>…</style>Single-page demos, critical CSS
Inline stylestyle='color:red'Almost never; beats the cascade and cannot be reused
<head>
  <link rel='stylesheet' href='/assets/app.css'>
</head>
πŸ’‘
Link your stylesheet in the <head>. Loading it later risks a visible flash of unstyled content.

Anatomy of a rule

/* selector { declaration; declaration } */
h1 {
  font-size: 2rem;
  line-height: 1.2;
}

Whitespace and line breaks are free β€” format for readability. Every declaration ends with a semicolon; forgetting one silently kills that declaration and the ones after it in the same block.

The cascade (why your style is ignored)

When several rules target one element, the browser resolves the conflict in this order β€” later steps win ties from earlier ones.

  1. Origin & importance β€” author styles beat user-agent defaults; !important flips that.
  2. Specificity β€” more targeted selectors win: inline > id > class/attribute/pseudo-class > element.
  3. Order β€” with equal specificity, whichever comes last in source order wins.
#nav .link { color: blue; }   /* id + class  β†’ highest */
.link        { color: red; }    /* class       */
a            { color: teal; }   /* element     */
⚠️
!important escapes the cascade entirely and cannot be overridden except by another !important in a higher-priority layer. Reach for it only to fix third-party styles you cannot edit.

Inheritance and the initial value

Some properties inherit down the tree naturally β€” color, font-family, line-height. Layout ones generally do not: margin, padding, border, width. You can force either behavior.

body { font-family: system-ui, sans-serif; color: #1a1a2e; }

.box {
  color: inherit;      /* take parent's value */
  margin: initial;     /* reset to default    */
  box-sizing: border-box;
}

That box-sizing: border-box line is so universally helpful that most projects apply it globally β€” it makes width include padding and border, which is how people intuitively expect sizing to work.

FAQ

Why does my external CSS not apply?
Check the file actually loads (Network tab), then the path. Root-relative paths like /assets/app.css break if you open the file with file://.
Should I use a CSS reset?
A light normalization is usually enough. Modern browsers are consistent; you mainly want box-sizing: border-box and margins zeroed where it matters.

Selectors and specificity The box model

Last refreshed 2026-09-17.