Adding CSS to HTML

CSS controls how HTML looks. There are three ways to attach it — an external stylesheet, a <style> element, and the style attribute — and each has its place. This lesson covers all three and the basics of how CSS targets HTML.

1. External stylesheets (recommended)

HTML external.html
<title>My site</title>
<link rel="stylesheet" href="css/styles.css">
CSS css/styles.css
body {
  font-family: system-ui, sans-serif;
  line-height: 1.6;
  max-width: 65ch;
  margin: 0 auto;
  padding: 1rem;
}

h1 {
  color: #d6336c;
}

A separate .css file can style every page on the site, so one edit updates them all. The browser caches it, making later pages load faster. This is the standard approach for real sites.

2. Internal styles

Try it yourself
Result

A <style> element (normally in the head) is handy for single-page demos, page-specific tweaks, and small amounts of critical CSS that should render instantly.

3. Inline styles

Try it yourself
Result

The style attribute applies CSS to one element. It's useful for values set by JavaScript or generated per item (like a progress bar's width), but avoid it for general styling: it can't be reused, mixes presentation into content, overrides other rules, and can't use media queries or hover states.

How CSS selects HTML

A CSS rule picks elements with a selector, then sets properties on them:

Try it yourself
Result
SelectorMatches
pEvery <p> element
.highlightElements with class="highlight"
#introThe element with id="intro"
nav a<a> elements inside a <nav>
a:hoverLinks being hovered over
input[type="email"]Inputs with that attribute value

Good HTML — semantic elements and meaningful class names — makes writing CSS far easier.

The cascade, briefly

When several rules set the same property on an element, the browser decides which wins by:

  1. Importance — !important declarations win (use rarely).
  2. Specificity — inline styles beat ids, ids beat classes, classes beat element names.
  3. Order — if all else is equal, the rule that comes last wins.

That's why the order of <link> tags matters: put your own stylesheet after any framework's stylesheet so yours can override it. The CSS course covers the cascade in depth.

Media attributes

HTML media.html
<title>Styles</title>
<link rel="stylesheet" href="print.css" media="print">
<link rel="stylesheet" href="wide.css" media="(min-width: 900px)">

A media attribute applies a stylesheet only in matching conditions — for printing, or for wide screens.

Browser default styles

Even without any CSS, browsers apply default styles: headings are bold and large, links blue and underlined, lists indented. Many projects start with a small "reset" or "normalize" stylesheet to make these defaults consistent across browsers before adding their own design.

Try it yourself

Try it yourself
Result