Add CSS to a page
Anatomy of a CSS rule
Read selectors, declaration blocks, properties, and values, then write small rules using valid CSS syntax.
A CSS rule has two parts: a selector that says which elements to style, and a declaration block that says how to style them.
.card {
padding: 1rem;
border: 1px solid black;
}
.card is the selector. The dot means “elements with this class”, so it picks every element whose class attribute contains card.
Everything between the braces is the declaration block. It holds two declarations. Each one is a property (padding), a colon, and a value (1rem). A semicolon ends the declaration.
Technically the last semicolon before the closing brace is optional. I always add it anyway. When you add another declaration later, you won’t forget it and wonder why the new line does nothing.
Whitespace is up to you
CSS doesn’t care about spaces and line breaks between tokens. This is the same rule, squeezed onto one line:
.card{padding:1rem;border:1px solid black}
The browser reads both the same way. Build tools often produce the compact form to save bytes. For the code you write and read, use the expanded form. One declaration per line is much easier to scan, and when something looks wrong you can spot it in seconds.
Some values have several parts separated by spaces, like 1px solid black above. That’s one value for the border property. It’s a shorthand, a property that sets several things at once. We’ll meet many of those.
Mistakes fail quietly
Here’s something that surprises people coming from JavaScript. Look at this rule:
.card {
paddng: 1rem;
border: 1px solid black;
color: darkblu;
}
Nothing crashes. No error shows up on the page. The browser drops the misspelled paddng property, drops the invalid darkblu value, and keeps the border.
This is by design. It lets old browsers skip properties they don’t know and still render the rest of the page. It’s part of what makes CSS resilient.
The flip side is that a typo can hide for a long time. If a declaration seems to have no effect, the first thing I check is the spelling. DevTools helps here: an invalid declaration shows up in the Styles panel with a warning icon and a line through it. We’ll look at that panel in detail in a couple of lessons.
Lesson completed