What you'll learn
What CSS does, how a style rule is written, and how to attach styles to a page.
Why it matters
HTML says what things are. CSS says how they look: colours, spacing, fonts and layout. Without CSS every site would look like a plain text document.
Explanation
CSS stands for Cascading Style Sheets. It is a list of rules. Each rule has:
- a selector: which elements to style (
h1,p). - a declaration block in curly braces holding one or more declarations.
- each declaration is a property and a value, written
property: value;.
h1 {
color: tomato;
font-size: 40px;
}You can add CSS to a page in three ways. The most common for real projects is a separate file linked from the page, but while learning we use a <style> tag placed in the HTML.
Example
<style>
h1 {
color: tomato;
font-size: 36px;
}
p {
color: #444;
font-family: Georgia, serif;
}
</style>
<h1>Styled heading</h1>
<p>This paragraph is also styled.</p>Step-by-step walkthrough
- The
<style>tag tells the browser "CSS lives in here". - The first rule selects every
<h1>and sets its colour and size. - The second rule selects every
<p>, giving it a dark grey colour and a serif font. - The browser applies each rule to every matching element on the page.
Try it yourself
Change tomato to royalblue and the heading size to 60px. Then add a rule that gives p a font-size of 20px.
Your first CSSHTML / CSS
Common mistakes
- Missing semicolon at the end of a declaration. The next line may be ignored.
- Colon vs equals. CSS uses
property: value, neverproperty = value. - Misspelled property names such as
colour. CSS uses American spelling:color. - Missing closing brace, which breaks every rule after it.
Quick quiz
Summary
- A CSS rule is
selector { property: value; }. - The selector chooses elements, declarations style them.
- A
<style>tag (or a linked file) delivers the CSS.
Next: choosing exactly which elements to style.