- Home
- /
- Tutorials
- /
- CSS Tutorial
- /
- CSS Syntax
CSS Introduction
CSS Syntax
Understand selectors, declaration blocks, properties, values, parsing, and the rules the browser follows when it reads a CSS stylesheet.
Every CSS rule has the same shape: a selector that says what to style, then curly braces with property: value pairs inside, each ending in a semicolon. Learn that one shape and you can read any stylesheet.
If you are new to CSS, start with What is CSS, and see How to Add CSS for where the rules go.
Basic Syntax Structure
css
selector {
property: value;
}Basic CSS Example
css
h1 {
color: red;
font-size: 24px;
}h1is the selector: which elements to style.{ }is the declaration block.color: red;is a declaration: the propertycolor, a colon, the valuered, and a semicolon.- One rule can hold as many declarations as you like.
Mistakes that break a rule
- A missing semicolon between two declarations:
color: red font-size: 24pxmakes both invalid. - A missing closing brace
}can swallow the rules that follow it. - A typo in a property, like
colourorfont-colour, is silently ignored. - A missing unit:
width: 200does nothing; it must be200px(zero is the exception:0needs no unit).
How browsers handle errors
Browsers normally discard an invalid declaration while continuing to parse the rest of the rule. This fault tolerance makes progressive enhancement possible: place a dependable declaration first, then a newer value for browsers that understand it. An unmatched brace or malformed selector can affect a larger region, so use developer tools or a CSS validator when later rules unexpectedly stop applying.
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>CSS Syntax Example</title>
<style>
h1 {
color: blue;
text-align: center;
}
p {
color: green;
font-size: 18px;
}
</style>
</head>
<body>
<h1>CSS Syntax</h1>
<p>This paragraph is styled using proper CSS syntax.</p>
</body>
</html>The heading is blue and centered, and the paragraph green at 18px.
Browser Support
Feature | Chrome | Edge | Firefox | Safari |
|---|---|---|---|---|
| CSS declarations | 1 | 12 | 1 | 1 |
Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.
Good to know
- Property names and most values are not case-sensitive, but class names in selectors are.
.Boxdoes not matchclass="box". - Comments are written
/* like this */.//does not work in CSS. - Put each declaration on its own line. It is easier to read and to spot mistakes.
CSS Syntax exercises
Every paragraph
Make every paragraph teal.
The HTML your code works on
<div id="wrap">
<h2 id="title">News</h2>
<p class="lead">Rain today.</p>
<p>Wind tomorrow.</p>
<a href="#">More</a>
</div>Result
