CSS Syntax

CSS syntax is the set of rules that defines how CSS code is written. Every CSS rule consists of a selector and a declaration block. Understanding CSS syntax is the foundation of styling web pages.

Basic CSS Syntax Structure

A CSS rule is made up of three main parts: a selector, a property, and a value.

selector {
  property: value;
}
    

Example of CSS Syntax

The following example styles all paragraph elements by changing their color and font size.

p {
  color: blue;
  font-size: 16px;
}
    

CSS Declaration Block

The declaration block contains one or more declarations separated by semicolons. Each declaration includes a property and a value.

h1 {
  color: green;
  text-align: center;
}
    

Multiple CSS Declarations

You can apply multiple styles to the same selector by adding more property-value pairs.

div {
  background-color: lightgray;
  padding: 20px;
  margin: 10px;
  border: 1px solid black;
}
    

CSS Syntax Rules

CSS Syntax and Readability

Writing clean and readable CSS syntax helps in maintaining large projects. Proper indentation and spacing make CSS easier to understand and debug.

.button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
}
    

Common Mistakes in CSS Syntax

Tip: Always validate your CSS syntax. A single syntax error can break the entire stylesheet.