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
| Method | How | When |
|---|---|---|
| External file | <link rel='stylesheet' href='app.css'> | Default choice β cacheable, reusable |
| Internal block | <style>β¦</style> | Single-page demos, critical CSS |
| Inline style | style='color:red' | Almost never; beats the cascade and cannot be reused |
<head>
<link rel='stylesheet' href='/assets/app.css'>
</head><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.
- Origin & importance β author styles beat user-agent defaults;
!importantflips that. - Specificity β more targeted selectors win: inline > id > class/attribute/pseudo-class > element.
- 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?
/assets/app.css break if you open the file with file://.Should I use a CSS reset?
box-sizing: border-box and margins zeroed where it matters.Related
Selectors and specificity The box model
Last refreshed 2026-09-17.