Sub topic 1
Anatomy of a CSS rule
Prerequisites
This chapter assumes you can do the following:
- Read basic HTML: elements, attributes, and how elements nest inside each other.
- Link or embed a stylesheet, either with a
<link rel="stylesheet">element or a<style>element. - Recognize simple CSS properties and values such as
color: redandmargin: 1rem.
You do not need to know anything about specificity or the cascade yet. This chapter lays the groundwork for both.
What a rule is
A stylesheet is a list of rules. The most common kind is the style rule. It says which elements to style and how to style them.
p.note {
color: #555;
margin-top: 0;
}This rule has two parts:
- The selector,
p.note, is a pattern. The browser tests every element in the document against it. - The declaration block is everything between
{and}. It holds a list of declarations.
Each declaration has a property name, a colon, a value, and a terminating semicolon. In color: #555;, color is the property and #555 is the value.
selector {
property: value;
property: value;
}The parts in detail
The selector
The selector decides which elements the rule applies to. It does not change how the declarations behave. Later chapters cover the kinds of selectors in depth. For now, treat p, .note, and #main as three different ways to name a set of elements.
A rule applies to every element the selector matches, not just the first. The selector p matches all paragraphs in the document, including paragraphs that appear after the stylesheet is loaded and are added by JavaScript.
The declaration block
The block is delimited by curly braces. Inside it, declarations are separated by semicolons. The semicolon after the last declaration is optional, but you should always write it. If you add a new declaration later and the old last one has no semicolon, the two merge into one broken declaration.
/* Broken: the missing semicolon merges two declarations */
.card {
color: navy
margin: 1rem;
}The browser reads navy margin: 1rem as one value for color. That is not a valid color, so it throws away the whole declaration. The margin setting is lost along with the color.
Properties and values
A property is a named style feature, such as color, margin, or font-size. A value is what you set it to. Values come in several types:
| Value type | Example | Used by |
|---|---|---|
| Keyword | `block`, `none`, `bold` | `display`, `font-weight` |
| Length | `16px`, `1.5rem`, `0` | `margin`, `width` |
| Color | `#555`, `rebeccapurple`, `rgb(0 0 0)` | `color`, `background` |
| Number | `1.5`, `0.8` | `line-height`, `opacity` |
| Function | `calc(100% - 2rem)` | many properties |
A value must be valid for its property. color: 12px is syntactically fine, but 12px is not a color, so the browser discards the declaration.
Shorthand properties
Some properties set several related properties at once. margin: 1rem 2rem; sets the top and bottom margins to 1rem and the left and right margins to 2rem. A shorthand also resets any sub-property you leave out. Writing background: teal; after background-image: url(a.png); on the same element removes the image, because the shorthand sets background-image back to none. This matters later, when we look at which rule wins.
Whitespace, case, and comments
CSS ignores extra whitespace and line breaks, so these two rules are identical:
h1{color:navy;margin:0}
h1 {
color: navy;
margin: 0;
}Property names and keyword values are not case sensitive, but the convention is lowercase. Some parts are case sensitive, including class names and ID names in selectors. .Note and .note match different elements.
Comments start with /* and end with */. They can span several lines. CSS has no // line comment. A line such as // fix this is not a comment, and it can cause the next rule to be dropped.
How the browser handles mistakes
CSS is forgiving. Instead of stopping at an error, the browser discards the smallest unit it can and keeps reading.
- An invalid declaration is dropped. The other declarations in the same block still apply.
- An unknown property is dropped for the same reason. This is why you can use a new CSS feature and let older browsers ignore it.
- An invalid selector causes the whole rule to be dropped.
- A selector list (selectors separated by commas) is invalid as a whole if any one selector in it is invalid. The entire rule is ignored.
.ok {
color: green;
colour: red; /* unknown property: dropped */
margin: 1 rem; /* invalid value (space in the length): dropped */
}
h1, h2:nope, h3 { /* ":nope" is not a real pseudo-class */
color: crimson; /* the whole rule is ignored, h1 and h3 too */
}In the first rule, only color: green takes effect. In the second, none of the three headings gets the color. This is a common source of "my style is not applied" bugs.
> Use the developer tools to find these errors. Invalid declarations show up struck through, often with a warning icon.
The note above is only a reminder. The next callout states the practical rule.
Other kinds of rules
Style rules are not the only kind. An at-rule starts with @ and does something other than style a set of elements. Some at-rules, such as @media and @layer, contain style rules. Others, such as @import, are a single statement that ends with a semicolon.
@import url("base.css");
@media (min-width: 40rem) {
p.note {
color: #333;
}
}In this chapter and the next several, we focus on style rules. @layer returns near the end of the tutorial, because it changes which rule wins.
Where rules come from
A declaration can arrive from several places, and the browser considers all of them together:
- Author styles are the ones you write, in a linked file, a
<style>element, or astyleattribute. - User styles are preferences set by the person reading the page, such as a larger default font size.
- The user-agent stylesheet is the browser's built-in defaults. It is why headings are bold and links are blue and underlined before you write any CSS.
The style attribute is a special case. It holds only declarations, with no selector, because it is already attached to a single element.
<p style="color: red; margin: 0">One paragraph only.</p>Rules compete, and some values pass down
Two things happen after the browser matches selectors to elements.
First, several rules often match the same element and set the same property. The browser must pick one value. The process is called the cascade, and it takes up most of this tutorial.
Second, some properties pass from a parent to its children without any rule targeting the children. This is inheritance. If you set color on body, paragraphs inside it get that color unless something sets their color directly. Properties such as color, font-family, and line-height inherit by default. Properties such as margin, border, and background do not.
The diagram shows the overall flow.
Direct rules always beat inherited values. A rule that targets an element, even with the weakest possible selector, overrides what the element would inherit. The chapter on inheritance returns to this.
A worked example
Here is a small stylesheet applied to one page.
<body>
<h2>Tips</h2>
<p class="note">Save often.</p>
<p>Back up your work.</p>
</body>body {
color: #222;
font-family: system-ui, sans-serif;
}
p {
margin: 0 0 1rem;
}
p.note {
color: green;
font-weight: bold;
}Walk through it:
bodymatches one element. Itscolorandfont-familypass down to the heading and both paragraphs through inheritance.pmatches both paragraphs. Each gets a bottom margin of1rem. The heading is not ap, so it is untouched.p.notematches only the first paragraph. It setscolordirectly, so this paragraph is green, not the inherited#222. It also becomes bold.- The second paragraph has no direct
color. It stays#222.
Only the first paragraph has competing sources for color (one inherited, one direct). The next chapters explain how to predict outcomes when several direct rules compete.
Exercise
A stylesheet contains .title, h2::nope, .lead { color: red; }. ::nope is not a real pseudo-element. Which elements turn red, and why?
Show answer
None. A selector list is invalid as a whole if any selector in it is invalid, so the browser drops the entire rule, including the valid .title and .lead selectors.
Exercise
What happens to the margin setting in .card { color: navy margin: 1rem; }, where the semicolon after navy is missing?
Show answer
It is lost. The browser reads navy margin: 1rem as a single value for color, finds it invalid, and drops that whole declaration. Neither the color nor the margin is applied.
Exercise
You set color: teal on body and nothing else. A paragraph inside body shows teal text. Which mechanism produced this, and would the same approach work for margin?
Show answer
Inheritance passed color from body to the paragraph. It would not work for margin, because margin is not inherited by default.