Sub topic 2
Anatomy of a CSS rule
This chapter assumes you know basic HTML structure (html, head, body, common elements). It also assumes you can edit and save a text file and open it in a browser. You do not need to know where CSS lives yet. Later chapters cover the three ways to attach it. Here you learn the unit that all three methods share: the rule.
Why the rule matters
Whether CSS sits in a style attribute, a <style> element, or a .css file, the browser reads the same grammar. Once you can read one rule precisely, you can read any stylesheet. You can also predict how the browser handles a typo, because CSS has specific error-recovery behavior. The behavior differs from HTML, and it differs again from most programming languages.
The parts of a rule
A CSS rule, also called a rule set or style rule, has two parts. The selector says which elements the rule applies to. The declaration block says what to do to them.
p {
color: darkblue;
line-height: 1.5;
}Here is each piece:
pis the selector. It matches every<p>element in the document.{ ... }is the declaration block. The curly braces enclose zero or more declarations.color: darkblue;is a declaration. It is one instruction.coloris the property, the aspect of the element you want to change.darkblueis the value, the setting you want for that property.:separates property from value.;ends the declaration.
Whitespace and formatting
Whitespace between tokens is mostly insignificant. These two rules are identical to the browser:
p{color:darkblue;line-height:1.5}
p {
color: darkblue;
line-height: 1.5;
}Use the second form when you write by hand. Minifiers produce the first form for production. The last semicolon in a block is optional, but always write it. If you later add a declaration below, you will not accidentally create a missing-semicolon error.
Whitespace does matter inside some values and selectors. In a selector, div p (descendant) and div.p (an element with a class) mean different things. A space is also required around + inside calc().
Properties and values
CSS defines a fixed set of property names, such as color, margin, font-size, and display. Property names are case-insensitive, but the convention is lowercase with hyphens (kebab-case). Each property accepts only certain kinds of value. Common kinds are:
| Kind of value | Examples | Used by |
|---|---|---|
| Keyword | `bold`, `none`, `center` | `font-weight`, `display`, `text-align` |
| Color | `crimson`, `#336699`, `rgb(51 102 153)` | `color`, `background-color` |
| Length | `16px`, `1.5rem`, `50%` | `margin`, `width`, `font-size` |
| Number | `1.5`, `0` | `line-height`, `opacity` |
| String or URL | `"Hello"`, `url("img/bg.png")` | `content`, `background-image` |
| Function | `calc(100% - 2rem)`, `var(--gap)` | many properties |
A value that is valid for one property can be invalid for another. color: 16px is meaningless, and margin: crimson is too. The browser checks each declaration against the grammar of its own property.
Multi-part values and shorthands
Some properties take several values separated by spaces. Shorthand properties set several related properties at once:
.card {
margin: 1rem 2rem;
border: 1px solid #999;
font: italic bold 1rem/1.4 Georgia, serif;
}margin: 1rem 2rem sets top and bottom to 1rem, and left and right to 2rem. A shorthand also resets any longhand it covers that you leave out. For example, border: 1px solid #999 sets the border color, so it overrides an earlier border-color. This is a common source of surprise when rules overlap.
A comma separates alternatives or list items, not parts of one value. In font-family: Georgia, serif, the browser tries Georgia first and falls back to serif.
Selectors in brief
This chapter only introduces selectors enough to read a rule. The common simple selectors are:
| Selector | Matches |
|---|---|
| `p` | Every `<p>` element (type selector) |
| `.note` | Every element with `class="note"` |
| `#intro` | The element with `id="intro"` |
| `*` | Every element |
You can combine selectors. p.note matches paragraphs that also have the class note. article p matches paragraphs inside an article.
Selector lists
To apply one declaration block to several selectors, separate them with commas:
h1,
h2,
h3 {
font-family: Georgia, serif;
margin-bottom: 0.5em;
}This is shorthand for three separate rules with the same block. Be careful here, because in a standard selector list one invalid selector makes the whole rule invalid. A typo in h3 would stop h1 and h2 from being styled too. If a rule mysteriously does nothing, check each selector in the list.
Comments
CSS has one comment syntax. It starts with /* and ends with */, and it can span lines:
/* Typography */
body {
font-family: system-ui, sans-serif; /* falls back to the default sans-serif */
}Double-slash // is not a CSS comment. If you write // note before a rule, the browser treats it as part of the next selector, and that rule can silently break.
// This is wrong in plain CSS
p {
color: red;
}In this example the selector becomes // This is wrong in plain CSS p, which matches nothing, so the paragraph stays unstyled.
How the browser handles errors
CSS is forgiving by design. The browser does not stop at the first problem. It discards the part it cannot understand and carries on. This keeps old browsers working with new CSS, but it also hides your mistakes.
An invalid declaration is dropped
p {
color: darkblue;
colour: red; /* unknown property: ignored */
margin: crimson; /* invalid value for margin: ignored */
line-height: 1.5;
}The paragraph gets color: darkblue and line-height: 1.5. The two invalid declarations are skipped, and no error appears on the page. Developer tools show them struck through (a later chapter covers that).
A missing semicolon merges declarations
p {
color: darkblue
line-height: 1.5;
}The browser reads darkblue line-height: 1.5 as a single value for color. That value is invalid, so the whole declaration is dropped. You lose both the color and the line height from a single missing character.
Fallback values on purpose
Because invalid declarations are ignored, you can write a safe value first and a newer one after it:
.box {
width: 90%;
width: min(90%, 40rem);
}A browser that understands min() uses the second declaration, because it comes later. A browser that does not understand it drops that line and keeps 90%.
Unknown values in the middle of a block
A broken declaration affects only itself. The parser skips ahead to the next semicolon, or to the closing brace if there is no semicolon. A stray unmatched { or } is more serious. It can swallow or terminate later rules, so keep braces balanced.
Rules versus at-rules
Not everything in a stylesheet is a style rule. An at-rule starts with @ and gives instructions to the browser. These are two examples:
@media (min-width: 40rem) {
p {
font-size: 1.125rem;
}
}
@import url("reset.css");@media wraps ordinary rules inside a condition. @import loads another stylesheet and ends with a semicolon, not a block. At-rules follow their own grammar, and the later chapter on @import covers that one. For now, remember that a style rule is "selector plus declaration block", and anything starting with @ is something else.
Rules without selectors: the style attribute
An inline style has a selector-free form. The style attribute contains only declarations, because the element it sits on is already the target:
<p style="color: crimson; font-weight: bold;">Styled by declarations only.</p>You cannot put a selector or braces inside the attribute. This is invalid and will not work:
<p style="p { color: crimson; }">Not valid.</p>The same grammar rules apply as in a block. Declarations are separated by semicolons, and an invalid one is dropped without stopping the others. The attribute value is also HTML, so a double quote inside it must be avoided or written as ". Use single quotes inside CSS strings there, for example font-family: 'Open Sans', sans-serif;.
A complete worked example
This page uses one rule to show everything above. Save it as anatomy.html and open it in a browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Rule anatomy</title>
<style>
/* One selector list, one declaration block */
h1,
h2 {
font-family: Georgia, serif;
color: #336699;
}
.note {
border: 1px solid #999;
padding: 0.5rem 1rem;
colour: red; /* typo: ignored */
background-color: #f5f5f5;
}
</style>
</head>
<body>
<h1>Main heading</h1>
<h2>Subheading</h2>
<p class="note">This paragraph has a border and padding. The typo line does nothing.</p>
</body>
</html>Both headings use Georgia and a blue color. The .note paragraph gets its border, padding, and background. The misspelled colour is discarded, so the text stays the default color.
Summary of terms
- A rule is a selector plus a declaration block.
- A declaration is a property, a colon, a value, and a semicolon.
- A selector list uses commas, and one invalid selector can invalidate the whole rule.
- Invalid declarations are dropped, and the rest of the block still applies.
- At-rules start with
@and are not style rules. - The
styleattribute holds only declarations.
Exercise
This rule has two mistakes. Name them and say what the browser does with each: p { color: blue line-height: 1.6; font-size: 1rem; }
Show answer
The semicolon after "blue" is missing, so the browser reads "blue line-height: 1.6" as one invalid value for color and drops that whole declaration, which loses both color and line-height. The other mistake is that nothing closes the rule: the closing brace is present, but if you meant "colour" or similar typos exist they would simply be ignored. Strictly, the only real mistake is the missing semicolon. font-size: 1rem still applies.
Exercise
A stylesheet starts with the line "// Site styles" followed by "h1 { color: green; }". Why does the h1 stay unstyled, and how do you fix it?
Show answer
CSS has no // comment. The browser treats "// Site styles h1" as the selector, which matches nothing. Replace the line with / Site styles / so the h1 rule parses normally.
Exercise
Write the contents of a style attribute that makes text bold and 1.25rem in size. Can you include a selector?
Show answer
style="font-weight: bold; font-size: 1.25rem;" No, you cannot include a selector or braces. The attribute holds only declarations, and the element it sits on is the target.