Rules, declarations and linking CSS

CSS · Essentials · 7 min

Everything in CSS is written as rules, so reading and placing them correctly comes first.

A stylesheet is a list of rules. Each rule has a selector that picks elements and a block of declarations, each a property: value; pair.

h1 { color: navy; font-size: 2rem; }

There are three ways to apply CSS to a page:

  • External stylesheet: <link rel="stylesheet" href="styles.css"> in the head. The normal choice: one file, cached by the browser, shared by every page.
  • Style element: <style>...</style> in the head, handy for small demos or critical CSS inlined for speed.
  • Inline style: <p style="color: red">. It applies to one element and beats almost every stylesheet rule, so it's hard to override. Avoid it except for values set by JavaScript.

Browsers are forgiving: a declaration with an unknown property or invalid value is dropped silently and the rest of the rule still applies. That's how newer features can be used with fallbacks, by writing the old value first and the new one second. It also means typos fail quietly, so the browser's devtools are essential: the Styles panel shows invalid declarations struck through with a warning icon.

Comments are /* ... */; there are no // line comments in CSS. At-rules start with @, such as @media, @import, @font-face and @layer, and configure how and when other rules apply.

Example

/* styles.css, linked with <link rel="stylesheet" href="styles.css"> */
body {
  font-family: system-ui, sans-serif;
  margin: 0;
}

h1, h2 {                 /* one rule, two selectors */
  color: #1e3a8a;
  line-height: 1.2;
}

.notice {
  colr: red;             /* typo: ignored, devtools shows a warning */
  background: #fef3c7;
  background: oklch(96% 0.05 90);  /* newer syntax overrides if supported */
}

Remember

  • A rule = selector + { property: value; } declarations
  • Prefer external stylesheets; avoid inline styles
  • Invalid declarations are dropped silently: check devtools

Watch out for

  • Writing // comments, which break the following rule.

Check yourself

  1. A rule contains 'color: blu; font-weight: bold;'. What happens?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics/What_is_CSS