CSS Tutorial for Beginners: Your First Style Rules
HTML says what a page contains: a heading, a paragraph, a list. CSS (Cascading Style Sheets) says how that content should look: its color, size, spacing and position. Keeping the two apart is the whole point. You can restyle an entire site by editing one stylesheet, without touching a single line of markup.
Anatomy of a rule
A stylesheet is a list of rules. Each rule has a selector, which picks elements, followed by a block of declarations in curly braces:
h1 {
color: #0e7490;
font-size: 2rem;
}
Read it as "for every h1, set color to #0e7490 and font-size to 2rem". Each declaration is a property, a colon, a value and a semicolon. The semicolon after the last declaration is optional, but always writing it saves you from a classic bug when you add another line later. Property names are lowercase words joined with hyphens, such as background-color or line-height.
Three ways to attach CSS
- External stylesheet: put rules in a file such as
styles.cssand link it from the<head>with<link rel="stylesheet" href="styles.css">. This is what real sites use, because every page shares one cached file. - A
<style>element in the<head>: handy for demos and single pages. Our examples use it so everything fits in one editor. - The
styleattribute on one element, like<p style="color: red">. It only affects that element and is hard to maintain, so keep it for quick experiments.
The example below uses a <style> element with three rules. The small script at the end asks the browser which color it actually computed for the heading, so you can see the rule took effect. Press Run, then change #0e7490 to another color and run it again.
Expected page text
Hello, CSS This paragraph is styled by a type selector. This one also matches the .note class. h1 color: rgb(14, 116, 144)
Notice that the browser reports the color as rgb(...), even though we wrote a hex code. CSS has several ways to write the same color, and computed values are always given in one normalized form. The colors chapter covers this.
Comments and whitespace
Comments go between /* and */ and can span lines. There is no // single-line comment in CSS; a stray // quietly breaks the next rule. Spaces and line breaks between tokens do not matter, so h1{color:red} and the spaced-out version above are identical to the browser.
When something is wrong
CSS is forgiving: if the browser does not understand a declaration, it skips that one declaration and carries on. A misspelled property (colr: red) or an invalid value (color: 12px) simply does nothing. That is why styles sometimes "silently" fail. The fix is to check spelling and use your browser's developer tools, which strike through declarations they rejected.
Summary
- A rule is a selector plus a block of
property: value;declarations. - Link an external
.cssfile for real sites;<style>andstyle=""are for small cases. - Invalid declarations are ignored one by one, not the whole stylesheet.
Quiz: Get started