CSS Syntax and Basic Selectors
Learn how a CSS rule is written, then target elements with type, class, ID, universal and grouped selectors, and add comments to your code.
What you will learn
Every piece of CSS you will ever write is built from the same simple pattern: a selector that picks elements and a declaration block that styles them. In this lesson you will learn that pattern exactly, then learn the five basic selectors (type, class, ID, universal and grouped) and how to write comments. After this lesson you can style any element on any page.
The anatomy of a CSS rule
A CSS rule has two parts: which elements and what styles.
h1 {
color: tomato;
font-size: 32px;
}
Here is what each piece is called:
h1 { <- selector (which elements?)
color: tomato; <- declaration: property + value
font-size: 32px; <- another declaration
} <- end of the declaration block
- The selector (
h1) chooses the elements to style. - The declaration block is everything between the curly braces
{ }. - A declaration is one style instruction: a property (
color), a colon:, a value (tomato) and a semicolon;.
Read it out loud like a sentence: “For every h1, set the color to tomato and the font-size to 32px.”
The rules of the grammar
CSS is forgiving about spacing but strict about punctuation:
- Every declaration ends with a semicolon. Technically the last one can skip it, but always add it. Otherwise the next line you add will break.
- A colon separates the property from the value, not an equals sign.
color = redis wrong;color: redis right. - Curly braces come in pairs. One missing
}can break every rule after it. - Whitespace and line breaks are ignored. These two rules are identical to the browser, but the second one is much easier to read:
p{color:gray;font-size:18px;}
p {
color: gray;
font-size: 18px;
}
- Property names are lower case and words are joined with hyphens:
background-color,font-size,border-radius. (NotbackgroundColorand notbackground_color.) - Numbers need units in most cases.
font-size: 20pxworks;font-size: 20does not. The one main exception is0, which needs no unit. Units get their own lesson.
Tip: put each declaration on its own line and indent it by two spaces. It costs nothing and makes bugs much easier to spot.
Comments
A comment is a note for humans that the browser ignores. CSS comments start with /* and end with */:
/* Styles for the page heading */
h1 {
color: tomato;
}
p {
color: gray;
/* font-size: 30px; */
}
Comments are useful in two ways: to explain why you wrote something, and to switch a declaration off temporarily without deleting it (like the font-size line above). A comment can span several lines.
Careful: CSS has only
/* */comments.// this is a commentis a JavaScript style and does not work in CSS. It breaks the rule after it.
Selectors: choosing what to style
The selector decides which elements a rule applies to. There are many kinds; these five cover most of what you will write at first. All the examples below run against the fruit shop page in Practice in Editor.
1. Type selector (by element name)
Write the name of an HTML element, and every element of that type is styled:
p {
color: gray;
}
li {
font-size: 20px;
}
That colours both paragraphs gray and enlarges all list items. Type selectors are perfect for base styles, but too broad when you want to style only some elements of a type.
2. Class selector (by class name)
A class lets you pick specific elements. In HTML, add a class attribute. In CSS, write a dot followed by the class name:
<li class="fruit sale">Banana</li>
.sale {
color: crimson;
font-weight: bold;
}
Now only elements with class="sale" (the banana and the orange) are red and bold. Notes on classes:
- Classes are reusable. Any number of elements can share one class.
- An element can have several classes, separated by spaces. The banana has two:
fruitandsale. It receives the styles from both. - Class names are case-sensitive and cannot contain spaces. The common convention is lower case with hyphens:
main-title,sale-badge. - Choose names that describe what the thing is, not how it looks.
.saleis better than.red-bold, because if you later change the look, the name still makes sense.
.fruit {
font-size: 22px;
}
.intro {
font-style: italic;
}
The .intro rule styles the first paragraph only, even though the last paragraph is also a <p>. This is exactly what classes are for.
3. ID selector (by id)
An id identifies one single element on the page. In CSS, write a hash # followed by the id:
<h1 id="page-title">Fruit Shop</h1>
#page-title {
text-align: center;
color: darkgreen;
}
Rules for IDs:
- An
idmust be unique: only one element per page can have it. - IDs are very strong selectors (you will see why in the Specificity lesson), which makes them hard to override later. For that reason most developers style with classes and keep IDs for links to sections of a page and for JavaScript.
4. Universal selector
The asterisk * matches every element:
* {
font-family: sans-serif;
}
Every element on the page now uses a sans-serif font. You will most often see * used for page-wide resets, which you will meet in the CSS Reset and box-sizing lesson.
5. Grouping selectors
If several selectors need the same styles, separate them with commas instead of copy-pasting the block:
h1,
h2 {
color: darkgreen;
text-align: center;
}
That is the same as writing two separate rules with identical declarations, but shorter and easier to maintain. You can group any kinds of selector together: h1, .intro, #footer.
Remember the punctuation: nothing for an element (
p), a dot for a class (.sale), a hash for an id (#page-title).
When two rules disagree
What if a p is gray from one rule and blue from another?
p {
color: gray;
}
.intro {
color: royalblue;
}
The intro paragraph is blue. A class selector is stronger than a type selector, so it wins no matter which order you wrote them in. When two selectors are equally strong, the later one wins (you saw this in the first lesson). The full system is the topic of the Specificity and the Cascade lesson.
Putting it together
Here is a complete stylesheet for the fruit shop page using every idea from this lesson:
/* Base styles for the whole page */
* {
font-family: sans-serif;
}
/* Headings share the same look */
h1,
h2 {
color: darkgreen;
}
#page-title {
text-align: center;
}
p {
color: gray;
}
.intro {
font-style: italic;
color: royalblue;
}
.fruit {
font-size: 22px;
}
.sale {
color: crimson;
font-weight: bold;
}
Common mistakes
- Forgetting the dot for a class (
sale { }looks for an element called<sale>) or using a hash for a class (#sale). Dot for class, hash for id. - A missing semicolon. The browser then merges two lines into one invalid declaration and ignores both.
- A missing closing brace
}, which breaks the rules after it. - Using
=instead of:, or a comma instead of a semicolon between declarations. - Using
//for comments instead of/* */. - Misspelling a property, for example
colourorfont-colour. CSS never shows an error message; the line just silently does nothing. DevTools will show it crossed out. - Leaving out the unit, as in
font-size: 20. - Putting a space in a class name.
class="fruit sale"is two classes, not one class called “fruit sale”. - Using the same
idon several elements. It usually appears to work, but it is invalid HTML and causes strange bugs.
Practice
-
Click Practice in Editor. Add a
.fruitrule that setsfont-size: 22px, and see what changes. -
Add a new class
freshto the Mango in the HTML, then write a.freshrule that makes itdarkgreen. -
Use a grouped selector to give the
h1andh2the same colour and centre them withtext-align: center. -
Make the intro paragraph italic using a class, without changing the last paragraph.
-
Comment out one declaration to switch it off, then bring it back.
-
Find and fix the four bugs in this stylesheet (use DevTools if you get stuck):
sale { color: crimson font-weight: bold; } h1, h2 { text-align = center; } // make the intro blue .intro { color: royalblue; }
Recap
- A CSS rule is a selector plus a declaration block
{ }holding one or moreproperty: value;declarations. - Each declaration ends in a semicolon; property and value are separated by a colon.
- Comments are written
/* like this */. - Type selector (
p) styles every element of that type; class (.sale) styles chosen elements and is reusable; ID (#page-title) targets one unique element. *matches everything, and commas group selectors that share styles.- Prefer classes for styling; keep IDs for links and JavaScript.
- Next you will learn how to describe colours in CSS.