Adding CSS & Syntax
CSS is a list of rules. Each rule picks some elements with a selector and sets properties on them. This lesson covers the syntax of a rule, the three ways to connect CSS to HTML, comments, and how to keep stylesheets readable.
Anatomy of a rule
h1 {
color: navy;
font-size: 32px;
}
h1— the selector: which elements to style.{ … }— the declaration block.color: navy;— a declaration: a property, a colon, a value, and a semicolon.
Whitespace and line breaks don't matter, but the convention is one declaration per line, indented. The semicolon after the last declaration is optional — include it anyway, so adding another line later doesn't break anything.
Three ways to add CSS
1. External stylesheet (recommended)
<title>My site</title> <link rel="stylesheet" href="styles.css">
One file styles every page and is cached by the browser. This is how real sites work.
2. Internal style element
<title>One page</title> <style> p { line-height: 1.6; } </style>
Styles for a single page — useful for demos and page-specific tweaks.
3. Inline style attribute
<p style="color: crimson; font-weight: bold;">Inline styles affect one element only.</p>
Hard to maintain and impossible to reuse; keep them for values set by JavaScript.
Multiple declarations and selectors
A comma between selectors applies one block to several selectors — here, both h2 and h3.
Comments
/* ========================== Buttons ========================== */ .button { padding: 8px 16px; /* vertical then horizontal */ /* border: 2px solid red; disabled while testing */ }
CSS comments start with /* and end with */; they can span lines. There's no // line comment in plain CSS. Use comments to label sections of long stylesheets and to explain non-obvious decisions.
Invalid declarations are skipped
When the browser meets something it doesn't understand — a typo, an unsupported property, an invalid value — it ignores that one declaration and carries on. That makes CSS forgiving and future-proof, but also means mistakes fail silently. Developer tools show ignored declarations crossed out with a warning icon.
Case and naming
- Properties and keywords are case-insensitive, but always written in lowercase.
- Class names and ids are case-sensitive:
.Carddoesn't matchclass="card". - Property names use hyphens:
background-color,font-size.
Shorthand properties
/* Longhand */ .box { margin-top: 10px; margin-right: 20px; margin-bottom: 10px; margin-left: 20px; } /* Shorthand — the same result */ .box { margin: 10px 20px; }
Many properties have shorthands that set several values at once: margin, padding, border, font, background, flex, grid. Be careful: a shorthand resets any values you leave out to their defaults.