CSS Syntax

Every CSS rule is built from a selector that picks elements and a declaration block that lists the styles to apply.

The shape of a rule

A CSS rule has two parts. The selector comes first and chooses which elements the rule affects. The declaration block follows inside curly braces and holds one or more declarations. Each declaration is a property and a value joined by a colon and finished with a semicolon.

A basic rule

<!DOCTYPE html>
<html>
<head>
<style>
p {
  color: green;
  text-align: center;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>

</body>
</html>

In that rule, <p> is the selector, while <color> and <text-align> are properties with the values <green> and <center>. The whole thing reads as: make every paragraph green and center its text.

Anatomy of a declaration

  • Property: the feature you want to change, such as color or font-size
  • Colon: separates the property from its value
  • Value: the setting you want, such as green or 16px
  • Semicolon: ends the declaration so another can follow

Semicolons and whitespace

CSS ignores extra spaces and line breaks, so you can format rules however reads best. The semicolon after each declaration is what matters. You may leave it off the very last declaration, but keeping it there prevents errors when you add another line later.

Multiple declarations

<!DOCTYPE html>
<html>
<head>
<style>
button {
  background-color: #00643c;
  color: white;
  padding: 10px 16px;
  border-radius: 6px;
}
</style>
</head>
<body>

<button>Subscribe</button>

</body>
</html>
Note: A missing semicolon or brace will cause the browser to skip the rest of a rule. If a style is not applying, check for a typo in the punctuation first.

Now that you can read a rule, learn how to aim it precisely in CSS Selectors.

Exercise: CSS Syntax

What are the two main parts that make up a CSS rule?