How CSS works

CSS is a list of rules. Each one names some elements and tells the browser how they should look.

A rule has three parts. The selector says which elements it applies to. Inside the braces come declarations, and each declaration is a property and a value separated by a colon and ended with a semicolon. That is the whole syntax — everything else is vocabulary.

There are three places to put it. A style attribute on a single element is the crudest: it applies to that one tag and nothing else, and it cannot be reused. A <style> block in the page applies to the whole document. A separate .css file linked with <link rel="stylesheet" href="…"> does the same, but the browser can cache it and every page can share it — which is why real sites use it and the other two stay for quick tests.

Selectors are how you aim. A bare name like p matches every paragraph. A dot matches a class, so .lead matches anything with class="lead" — classes exist for exactly this and you invent them yourself. A # matches an id, which must be unique on the page.

Put two selectors next to each other with a space and you get a descendant: nav a means "every link inside a nav, however deep", and leaves every other link alone. That combination is the one you will reach for most.

/* selector { property: value; } */

h1 {
  color: gold;
}

.card p {
  color: grey;
}
Every h1 turns gold; only the paragraphs inside a .card turn grey.

Exercises0/5

  1. 1Your first ruleselector { property: value }
  2. 2Where the CSS goes<style>account
  3. 3Aim at an elementelement selectoraccount
  4. 4Aim at a classclass selectoraccount
  5. 5Aim inside somethingdescendant selectoraccount
How CSS works — Beginner · CSS Duel