CSS has a simple, logical syntax that's easy to learn once you understand the basic structure. Every CSS rule follows the same pattern: select an element, then apply styles to it. Let's break down exactly how CSS code is written.
The Anatomy of a CSS Rule
A CSS rule (also called a rule set) consists of two main parts: a selector and a declaration block.
selector {
property: value;
property: value;
}Let's look at a real example:
h1 {
color: blue;
font-size: 24px;
text-align: center;
}Breaking it down:h1 is the selector (what to style){ } are curly braces that contain the stylescolor, font-size, text-align are properties (what aspect to change)blue, 24px, center are values (how to change it)
Each line ends with a ; semicolon
Understanding Selectors
Selectors are how you tell CSS which HTML elements to style. Think of them as the "target" of your styling rules.
Element Selectors
The simplest selector targets all instances of an HTML element by using the element name.
p {
color: gray;
line-height: 1.6;
}
h2 {
color: navy;
font-weight: bold;
}
a {
color: blue;
text-decoration: underline;
}Element Selectors in Action
Class Selectors
Class selectors target elements with a specific class attribute. They start with a period (.).
.highlight {
background-color: yellow;
padding: 5px;
}
.warning {
color: red;
font-weight: bold;
}
.success {
color: green;
border: 2px solid green;
padding: 10px;
}Class Selectors in Action
ID Selectors
ID selectors target a single unique element with a specific id attribute. They start with a hash symbol (#).
#header {
background-color: navy;
color: white;
padding: 20px;
}
#main-content {
max-width: 800px;
margin: 0 auto;
}
#footer {
background-color: #333;
color: white;
text-align: center;
padding: 15px;
}Important: IDs should be unique on a page. Use classes when you need to style multiple elements the same way, and reserve IDs for truly unique elements or JavaScript targeting.
Universal Selector
The universal selector (*) targets all elements on the page.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}This is commonly used to reset default browser styles and apply consistent box-sizing across all elements.
Properties and Values
Properties define what aspect of the element you want to style, and values specify how you want to style it.
Common CSS Properties
Essential CSS Properties
| Property | Values | Description |
|---|---|---|
color | color names, hex, rgb, hsl | Sets the text color |
background-color | color names, hex, rgb, hsl | Sets the background color |
font-size | px, em, rem, %, keywords | Sets the size of text |
font-family | font names, generic families | Sets the font typeface |
font-weight | normal, bold, 100-900 | Sets text thickness |
text-align | left, right, center, justify | Aligns text horizontally |
margin | px, em, rem, %, auto | Space outside the element |
padding | px, em, rem, % | Space inside the element |
border | width style color | Sets element border |
width | px, %, em, rem, auto | Sets element width |
height | px, %, em, rem, auto | Sets element height |
display | block, inline, flex, grid, none | Sets display behavior |
CSS Value Types
CSS values come in several types:
- Keywords: Predefined words like
center,bold,none - Length units:
px,em,rem,%,vw,vh - Colors:
red,#ff0000,rgb(255, 0, 0) - Numbers:
1.5,100(for properties like line-height or font-weight) - URLs:
url('image.jpg')for background images - Strings:
"Arial",'Times New Roman'for font names
div {
/* Keyword value */
display: block;
/* Length values */
width: 500px;
padding: 20px;
margin: 1.5em;
/* Color values */
color: navy;
background-color: #f0f0f0;
border-color: rgb(200, 200, 200);
/* Number value */
line-height: 1.6;
/* URL value */
background-image: url('pattern.png');
/* String value */
font-family: "Helvetica Neue", Arial, sans-serif;
}Multiple Declarations
You can apply multiple style declarations to the same selector. Each declaration is separated by a semicolon.
button {
background-color: #667eea;
color: white;
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: background-color 0.3s;
}Multiple Declarations on Buttons
💡 Pro Tip:
Always include a semicolon after each declaration, even the last one. While it's technically optional for the last declaration, it prevents errors when you add more styles later.
Grouping Selectors
When multiple selectors should have the same styles, you can group them together separated by commas. This helps keep your CSS DRY (Don't Repeat Yourself).
/* Instead of this: */
h1 {
font-family: Georgia, serif;
color: navy;
}
h2 {
font-family: Georgia, serif;
color: navy;
}
h3 {
font-family: Georgia, serif;
color: navy;
}
/* Do this: */
h1, h2, h3 {
font-family: Georgia, serif;
color: navy;
}Grouped Selectors Example
CSS Formatting and Style
While CSS is flexible with formatting, following consistent conventions makes your code more readable and maintainable.
Recommended Formatting
/* Good formatting */
selector {
property: value;
property: value;
property: value;
}
/* Each declaration on its own line */
.card {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* Use indentation for readability */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
/* Group related rules together */
/* Typography */
h1 {
font-size: 32px;
}
h2 {
font-size: 24px;
}
/* Layout */
.grid {
display: grid;
}
.flex {
display: flex;
}Avoid Poor Formatting
/* Hard to read - all on one line */
.button{background-color:blue;color:white;padding:10px;border:none;}
/* Inconsistent spacing */
.card{
background: white;
padding:20px;
border-radius: 8px;
box-shadow:0 2px 4px rgba(0,0,0,0.1);
}
/* No organization */
.header{color:red;}
.footer{color:blue;}
.header{font-size:24px;}
.sidebar{width:200px;}Best Practice: Use a code editor with CSS formatting tools (like Prettier) that automatically formats your code consistently. Most modern editors have built-in or plugin support for this.
CSS Comments
Comments in CSS are written between /* and */. They're ignored by the browser and are used to document your code or temporarily disable styles.
/* This is a single-line comment */
/*
This is a multi-line comment
You can write as much as you need
across multiple lines
*/
/* === TYPOGRAPHY === */
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
/* Main heading styles */
h1 {
color: navy;
font-size: 32px;
}
/* Temporarily disabled
.old-style {
background-color: red;
}
*/
/* TODO: Update these colors to match new brand */
.button {
background-color: blue; /* Primary brand color */
color: white;
}Comments are useful for:
- Explaining complex or unusual CSS
- Organizing sections of your stylesheet
- Temporarily disabling styles while testing
- Leaving notes for yourself or other developers
- Documenting browser-specific hacks or workarounds
Common Syntax Errors to Avoid
Here are some frequent mistakes beginners make when writing CSS:
1. Missing Semicolons
/* Wrong - missing semicolons */
.box {
color: red
background: blue
padding: 10px
}
/* Correct */
.box {
color: red;
background: blue;
padding: 10px;
}2. Missing Curly Braces
/* Wrong - missing closing brace */
.container {
width: 100%;
padding: 20px;
/* Correct */
.container {
width: 100%;
padding: 20px;
}3. Wrong Selector Syntax
/* Wrong - missing dot for class */
myclass {
color: red;
}
/* Wrong - missing hash for id */
myid {
color: blue;
}
/* Correct */
.myclass {
color: red;
}
#myid {
color: blue;
}4. Invalid Property Names
/* Wrong - invalid property names */
div {
textcolor: red; /* Should be: color */
font: 16px; /* Should be: font-size */
backgroundcolor: blue; /* Should be: background-color */
}
/* Correct */
div {
color: red;
font-size: 16px;
background-color: blue;
}5. Invalid Values
/* Wrong - invalid values */
div {
color: 20px; /* Color needs a color value, not size */
width: red; /* Width needs a length, not a color */
font-size: bold; /* font-size needs a size, not weight */
}
/* Correct */
div {
color: red;
width: 200px;
font-size: 16px;
}Debugging Tip: If your CSS isn't working, use your browser's Developer Tools (F12) to inspect elements and check if your styles are being applied. The browser will show you which rules are active and which are being overridden.
Practice Exercise
Try writing CSS rules for the following scenarios. You can test them in a code editor or browser:
- Create a rule that makes all paragraphs have gray text and a line height of 1.8
- Style elements with class "highlight" to have a yellow background and bold text
- Make all links blue with no underline, but underlined when hovered
- Create a rule for an element with id "header" that has a dark background, white text, and 20px padding
- Group h1, h2, and h3 to all use the same font family and color
🎯 Challenge:
Once you've written the CSS, try to create the matching HTML and see your styles in action! This hands-on practice is the best way to solidify your understanding of CSS syntax.
Key Takeaways
- CSS rules consist of a selector and a declaration block
- Selectors target HTML elements (element, .class, #id, *)
- Declaration blocks contain property-value pairs separated by semicolons
- Properties define what to style, values define how to style it
- Multiple selectors can share the same styles using commas
- Proper formatting makes CSS more readable and maintainable
- Comments (/* */) help document your code and organize stylesheets
- Common errors include missing semicolons, braces, or wrong selector syntax
- Browser Developer Tools are invaluable for debugging CSS
What's Next?
Now that you understand CSS syntax and how to write valid CSS rules, you're ready to learn the different ways to add CSS to your HTML documents. In the next lesson, we'll explore inline CSS, internal CSS, and external CSS files, and discuss when to use each method.
Understanding CSS syntax is fundamental—everything else you learn about CSS will build on these basics!