LearnContact
Lesson 314 min read

CSS Syntax

Learn the complete syntax of CSS, including selectors, declaration blocks, properties, values, comments, multiple declarations, formatting rules, and how browsers process CSS code.

Introduction

In the previous lesson, you learned how CSS works with HTML and how the browser matches CSS rules with elements.

Now it is time to understand how CSS code itself is written.

Just like every programming or styling language, CSS follows a specific structure and set of writing rules.

This structure is called CSS syntax.

A CSS rule normally contains a selector followed by a declaration block. The declaration block contains one or more declarations, and each declaration contains a property and a value.

Choose Element
Write Selector
Open Curly Brace
Write Property
Add Colon
Write Value
Add Semicolon
Close Curly Brace
Syntax is the Grammar of CSS

Correct syntax allows the browser to understand what should be selected and how it should be styled.

What is CSS Syntax?

CSS syntax is the set of rules that defines how CSS code must be written.

It determines where selectors, curly braces, properties, colons, values, and semicolons should appear.

Basic CSS Syntax
selector {
    property: value;
}

The selector identifies the HTML element or elements to style.

The declaration block contains the styling instructions.

Real CSS Rule
h1 {
    color: blue;
}
Syntax PartExamplePurpose
Selectorh1Selects HTML elements
Opening Brace{Starts the declaration block
PropertycolorIdentifies what should change
Colon:Separates property and value
ValueblueDefines the new setting
Semicolon;Ends the declaration
Closing Brace}Ends the declaration block
Remember the Pattern

Selector → Curly Braces → Property → Colon → Value → Semicolon.

Why Do We Need CSS Syntax?

The browser needs a predictable structure to understand CSS instructions correctly.

Without syntax rules, the browser would not know where a selector ends, where a declaration begins, or which value belongs to which property.

Without Correct Syntax

  • Browser may ignore declarations.
  • Styles may not appear.
  • Rules become difficult to read.
  • Debugging becomes confusing.
  • Unexpected results can occur.

With Correct Syntax

  • Browser understands the rules.
  • Styles apply correctly.
  • Code remains readable.
  • Errors are easier to find.
  • Stylesheets are easier to maintain.
Incorrect CSS
h1
    color blue
Correct CSS
h1 {
    color: blue;
}
Browsers Ignore Invalid CSS

When the browser cannot understand a declaration, it usually ignores that invalid declaration instead of stopping the entire webpage.

Real-World Analogy

Imagine ordering food at a restaurant.

You need to clearly identify the customer and provide the instruction in a format that can be understood.

Restaurant Instruction
Customer: Table 5
Food: Pizza
Size: Large

CSS follows a similar structure.

CSS Instruction
h1 {
    color: blue;
    font-size: 40px;
}
RestaurantCSS
Table 5Selector
FoodProperty
PizzaValue
SizeProperty
LargeValue
Complete OrderCSS Rule
Identify Target
Choose Property
Provide Value
Complete Instruction
Apply Result
Clear Instructions Produce Clear Results

CSS syntax gives the browser a structured way to understand styling instructions.

Basic CSS Syntax

The basic structure of a CSS rule contains two major parts: a selector and a declaration block.

CSS Rule Structure
selector {
    property: value;
}
Syntax Breakdown
h1      {      color      :      blue      ;
│              │                 │
│              │                 └── Value
│              │
│              └── Property
│
└── Selector

{ ... }  → Declaration Block

color: blue; → Declaration
HTML
<h1>
    Welcome to CSS
</h1>
CSS
h1 {
    color: blue;
}
h1 Selector
Find <h1>
Read color Property
Read blue Value
Apply Style

Parts of a CSS Rule

A complete CSS rule is made from several important parts.

Complete Rule
p {
    color: gray;
    font-size: 18px;
}
PartExampleMeaning
SelectorpElements to style
Declaration Block{ ... }Collection of declarations
Declarationcolor: gray;One styling instruction
PropertycolorWhat should change
ValuegrayHow it should change
Colon:Separates property from value
Semicolon;Ends a declaration
CSS Rule
Selector
Declaration Block
Declarations
Property + Value
A Rule Can Contain Many Declarations

One selector can have multiple property-value pairs inside the same declaration block.

1. Selector

The selector tells the browser which HTML element or elements should receive the styles.

Selector Example
h1 {
    color: purple;
}

Here, h1 is the selector.

It matches every <h1> element in the document.

HTML
<h1>
    First Heading
</h1>

<h1>
    Second Heading
</h1>

Because both elements match the h1 selector, both headings receive the purple color.

SelectorMatches
h1All <h1> elements
pAll <p> elements
buttonAll <button> elements
aAll <a> elements
Selectors Decide Who Gets Styled

The browser applies declarations only to elements that match the selector.

2. Declaration Block

The declaration block contains the styling instructions for the selected elements.

It begins with an opening curly brace and ends with a closing curly brace.

Declaration Block
{
    color: blue;
    font-size: 40px;
}
Complete CSS Rule
h1 {
    color: blue;
    font-size: 40px;
}

Everything between the curly braces belongs to the declaration block.

Structure
h1  {
      │
      ├── color: blue;
      │
      ├── font-size: 40px;
      │
      }
      
      Entire area between { and }
      is the Declaration Block
Do Not Forget Curly Braces

Curly braces separate the selector from its declarations and define where the rule begins and ends.

3. Property

A CSS property identifies the feature or characteristic that you want to change.

Property Examples
color: blue;
font-size: 20px;
background-color: yellow;
text-align: center;
PropertyControls
colorText color
font-sizeText size
background-colorBackground color
widthElement width
heightElement height
marginOuter spacing
paddingInner spacing
borderElement border
Using Properties
p {
    color: white;
    background-color: green;
    font-size: 20px;
}
Properties Answer "What?"

The property tells the browser what aspect of the element should change.

4. Value

A value defines the setting that should be assigned to a CSS property.

Property and Value
color: blue;

In this declaration, color is the property and blue is the value.

PropertyExample ValueResult
colorredRed text
font-size24px24-pixel text
text-aligncenterCentered text
width300px300-pixel width
background-coloryellowYellow background
Different Values
h2 {
    color: red;
    font-size: 32px;
    text-align: center;
}
Values Answer "How?"

The property identifies what should change, while the value defines the setting to use.

5. Colon & Semicolon

The colon and semicolon have different responsibilities inside a CSS declaration.

CSS Declaration
color: blue;
Breakdown
color    :    blue    ;
  │      │      │     │
  │      │      │     └── Ends Declaration
  │      │      │
  │      │      └── Value
  │      │
  │      └── Separates Property and Value
  │
  └── Property
SymbolNamePurpose
:ColonSeparates property and value
;SemicolonEnds a declaration
{Opening Curly BraceStarts declaration block
}Closing Curly BraceEnds declaration block
Multiple Declarations
p {
    color: blue;
    font-size: 18px;
    text-align: center;
}
Use the Correct Symbol

A colon separates the property from its value. A semicolon separates one declaration from the next.

Example 1: Single Declaration

A CSS rule can contain only one declaration.

HTML
<p>
    Learning CSS is interesting.
</p>
CSS
p {
    color: blue;
}
Browser Finds <p>
Matches p Selector
Reads color Property
Reads blue Value
Displays Blue Text
One Declaration, One Change

This rule changes only the text color because the declaration block contains only the color property.

Example 2: Multiple Declarations

A declaration block can contain multiple declarations.

HTML
<h1>
    Welcome to PrograMinds
</h1>
CSS
h1 {
    color: white;
    background-color: purple;
    font-size: 40px;
    text-align: center;
}
DeclarationEffect
color: white;Makes text white
background-color: purple;Makes background purple
font-size: 40px;Makes text 40 pixels
text-align: center;Centers the text
Match h1
Apply White Text
Apply Purple Background
Apply 40px Size
Center Text
Display Final Result

Writing Multiple CSS Rules

A stylesheet normally contains many CSS rules.

HTML
<h1>
    CSS Course
</h1>

<p>
    Learn CSS step by step.
</p>

<button>
    Start Learning
</button>
CSS
h1 {
    color: purple;
}

p {
    color: gray;
    font-size: 18px;
}

button {
    color: white;
    background-color: green;
}
Read First Rule
Style h1
Read Second Rule
Style p
Read Third Rule
Style button
Each Rule Has Its Own Target

Different selectors allow different groups of elements to receive different styles.

CSS Comments

Comments are notes written inside CSS code for developers.

The browser ignores CSS comments when applying styles.

CSS Comment Syntax
/* This is a CSS comment */
Comment with CSS Rules
/* Main page heading */

h1 {
    color: blue;
}

/* Introduction paragraph */

p {
    color: gray;
}
Multi-Line Comment
/*
    This section contains
    the styles for the
    main navigation.
*/

Good Comments

  • Explain why a rule exists.
  • Identify important sections.
  • Describe unusual behavior.
  • Help developers understand decisions.

Poor Comments

  • Repeat obvious code.
  • Contain outdated information.
  • Explain every simple declaration.
  • Create unnecessary clutter.
CSS Comments Are Different from HTML Comments

CSS uses /* ... */ while HTML uses <!-- ... -->.

Whitespace and Formatting

CSS generally allows flexible whitespace between many parts of a rule.

The following examples can represent the same CSS rule.

Readable CSS
h1 {
    color: blue;
    font-size: 40px;
}
Compact CSS
h1{color:blue;font-size:40px;}

Both can produce the same result, but the first version is much easier for developers to read and maintain.

Difficult to Read

  • Everything on one line.
  • No indentation.
  • Harder to find declarations.
  • Difficult to edit large rules.

Easy to Read

  • One declaration per line.
  • Consistent indentation.
  • Clear opening and closing braces.
  • Easy to scan and maintain.
Formatting is for Developers

The browser can understand compact CSS, but readable formatting makes development and maintenance easier.

Valid vs Invalid CSS

CSS must follow the expected syntax for declarations to be understood correctly.

Invalid

  • color blue;
  • font-size = 20px;
  • background-color;
  • width:;
  • text-align center;

Valid

  • color: blue;
  • font-size: 20px;
  • background-color: yellow;
  • width: 300px;
  • text-align: center;
Partially Invalid Rule
p {
    color: blue;
    font-size 20px;
    background-color: yellow;
}

The font-size declaration is invalid because the colon is missing.

The browser can ignore the invalid declaration while continuing to process valid declarations that it can understand.

Read Declaration
Check Syntax
Valid?
Yes → Apply
No → Ignore
Continue Reading
One Invalid Declaration Does Not Always Break Everything

Browsers are designed to recover from many CSS errors by ignoring declarations they cannot understand and continuing with the remaining code.

How Browser Reads CSS

The browser processes CSS rules in several stages.

CSS Rule
h1 {
    color: blue;
    font-size: 40px;
}
Read Selector
Find Matching Elements
Open Declaration Block
Read Property
Read Value
Validate Declaration
Store Applicable Style
Calculate Final Result
Browser StepAction
Read h1Recognizes the selector
Find elementsLocates matching <h1> elements
Read colorRecognizes the property
Read blueChecks the property value
Read font-sizeRecognizes another property
Read 40pxChecks the value
Apply ruleUses declarations in style calculation
Browsers Parse CSS

The browser does not display CSS code directly. It parses the code, understands the rules, matches elements, and calculates styles.

Browser Rendering Flow

CSS syntax is processed as part of the complete browser rendering process.

Load HTML
Build DOM
Load CSS
Parse CSS Syntax
Build CSSOM
Match Selectors
Resolve Cascade
Calculate Styles
Calculate Layout
Paint Output
CSS Processing Flow
CSS Code
   │
   ▼
Parse Syntax
   │
   ▼
Recognize Selectors
   │
   ▼
Recognize Declarations
   │
   ▼
Validate Properties & Values
   │
   ▼
Match HTML Elements
   │
   ▼
Resolve Competing Rules
   │
   ▼
Calculate Final Styles
   │
   ▼
Render Output
StagePurpose
Parse SyntaxUnderstand CSS structure
Read SelectorsIdentify possible target elements
Read DeclarationsIdentify styling instructions
Validate ValuesCheck whether declarations can be used
Match ElementsFind affected HTML elements
Resolve CascadeDetermine winning declarations
Calculate StylesCreate final property values
RenderDisplay the styled page

Real-World Applications

Correct CSS syntax is used in every website and web application that uses CSS.

Website Design

CSS rules control the visual presentation of website elements.

Responsive Interfaces

Correct syntax is required for responsive styling rules.

Components

Buttons, cards, forms, and navigation use reusable CSS rules.

Design Systems

Consistent declarations define shared visual patterns.

E-Commerce

Products, pricing, buttons, and layouts depend on structured CSS.

Learning Platforms

Lessons, code blocks, sidebars, and progress components use CSS rules.

Dashboards

Complex interfaces depend on readable and maintainable stylesheets.

Web Applications

Large applications may contain thousands of structured CSS declarations.

Write Correct Syntax
Browser Parses Rules
Selectors Match Elements
Declarations Apply
Interface Gets Styled

Advantages

Learning CSS syntax correctly provides a strong foundation for every advanced CSS topic.

Clear Understanding

You understand every part of a CSS rule.

Easier Debugging

Syntax mistakes become easier to identify.

Better Readability

Well-formatted rules are easier to understand.

Faster Development

Correct syntax reduces unnecessary debugging.

Better Maintenance

Structured code is easier to update.

Better Collaboration

Consistent formatting helps teams work together.

Advanced Learning

Selectors, layouts, animations, and responsive CSS all depend on syntax.

Predictable Results

Valid declarations are easier to reason about and test.

Common Beginner Mistakes

Forgetting the Selector

A standard CSS style rule needs a selector before its declaration block.

Forgetting Opening Curly Brace

The declaration block must begin with an opening curly brace.

Forgetting Closing Curly Brace

An unclosed rule can cause later CSS to be interpreted incorrectly.

Using Parentheses Instead of Curly Braces

CSS declaration blocks use { } rather than ( ).

Missing Colon

A colon must separate a property from its value.

Using Equal Sign

CSS declarations use a colon, not an equal sign.

Missing Property

A value cannot be used without a property name.

Missing Value

A property needs a valid value.

Forgetting Semicolons

Missing semicolons can cause following declarations to be parsed incorrectly.

Using Comma Between Declarations

Declarations are normally separated with semicolons, not commas.

Writing HTML Comment Syntax

CSS comments use /* ... */ rather than HTML comment syntax.

Using // Comments

Standard CSS does not use JavaScript-style // comments.

Writing Invalid Property Names

Unknown or misspelled properties are ignored.

Writing Invalid Values

A valid property may still be ignored when its value is invalid.

Writing Everything on One Line

Compact CSS may work but becomes difficult to maintain during development.

Inconsistent Indentation

Inconsistent formatting makes large stylesheets harder to scan.

Assuming Every Error Stops CSS

Browsers often ignore invalid declarations and continue processing the stylesheet.

Not Checking Developer Tools

Browser developer tools can reveal invalid, overridden, and applied declarations.

Best Practices

  • Write selectors clearly.
  • Place the opening curly brace after the selector.
  • Use a matching closing curly brace for every rule.
  • Write one declaration per line during development.
  • Indent declarations consistently.
  • Use a colon between every property and value.
  • End declarations with semicolons consistently.
  • Use valid CSS property names.
  • Use values supported by the selected property.
  • Keep spaces around syntax consistent.
  • Use readable formatting.
  • Avoid placing an entire large stylesheet on one line.
  • Use CSS comments with /* ... */.
  • Do not use HTML comment syntax inside CSS.
  • Do not use JavaScript-style // comments in standard CSS.
  • Use comments to explain important decisions.
  • Avoid comments that simply repeat obvious declarations.
  • Remove outdated comments.
  • Group related declarations together.
  • Group related CSS rules logically.
  • Keep selector formatting consistent.
  • Use lowercase property names.
  • Use meaningful values.
  • Check spelling carefully.
  • Check hyphens in multi-word property names.
  • Write background-color rather than background color.
  • Write font-size rather than font size.
  • Do not use equal signs between properties and values.
  • Do not use commas to separate normal declarations.
  • Do not place semicolons after selectors.
  • Do not place colons after selectors in normal style rules.
  • Do not forget the declaration block.
  • Keep braces balanced.
  • Use code editor bracket matching.
  • Use syntax highlighting.
  • Use automatic formatting when helpful.
  • Use a CSS validator when debugging difficult syntax problems.
  • Inspect invalid declarations in browser developer tools.
  • Check crossed-out declarations before changing code.
  • Understand the difference between invalid and overridden CSS.
  • An invalid declaration cannot be understood by the browser.
  • An overridden declaration may be valid but lose in the cascade.
  • Check whether a selector matches the intended element.
  • Check whether the property name is valid.
  • Check whether the value is valid.
  • Check whether a unit is required.
  • Check whether punctuation is missing.
  • Change one error at a time while debugging.
  • Keep examples small when learning syntax.
  • Practice writing rules without copying.
  • Learn the selector-declaration pattern.
  • Remember that a declaration contains a property and value.
  • Remember that a declaration block can contain many declarations.
  • Remember that a stylesheet can contain many rules.
  • Use meaningful comments to divide large stylesheet sections.
  • Keep formatting consistent across the project.
  • Follow the team formatting standard when working with others.
  • Use automated linting in larger projects when appropriate.
  • Do not ignore editor warnings.
  • Do not depend entirely on automatic correction.
  • Understand why a syntax error occurred.
  • Test CSS changes in the browser.
  • Use developer tools to experiment with declarations.
  • Copy successful experimental changes back into the source file.
  • Do not treat temporary developer-tools changes as permanent source changes.
  • Keep source CSS readable before production optimization.
  • Allow build tools to minify production CSS when appropriate.
  • Do not manually sacrifice readability only to reduce whitespace.
  • Learn valid syntax before learning shorthand properties.
  • Learn basic rules before complex selectors.
  • Learn declaration syntax before advanced layouts.
  • Practice multiple declarations.
  • Practice multiple CSS rules.
  • Practice CSS comments.
  • Practice finding syntax mistakes.
  • Read browser output after every important change.
  • Compare expected output with actual output.
  • Build a strong syntax foundation before moving to selectors.
Write for Humans and Browsers

CSS must be valid enough for the browser to understand and readable enough for developers to maintain.

Frequently Asked Questions

What is CSS syntax?

CSS syntax is the set of rules that defines how selectors, declaration blocks, properties, values, and punctuation are written.

What are the main parts of a CSS rule?

The two main parts are the selector and the declaration block.

What is a CSS selector?

A selector identifies the HTML elements that should receive the styles.

What is a declaration block?

A declaration block is the area between curly braces that contains one or more CSS declarations.

What is a CSS declaration?

A CSS declaration is a property-value pair such as color: blue;.

What is a CSS property?

A property identifies the characteristic that should be changed, such as color or font-size.

What is a CSS value?

A value defines the setting assigned to a property, such as blue or 20px.

Why is a colon used in CSS?

A colon separates a property name from its value.

Why is a semicolon used in CSS?

A semicolon ends a declaration and separates it from the next declaration.

Are semicolons always required?

The final declaration before a closing brace can often be parsed without one, but consistently writing semicolons is a good practice.

What do curly braces do?

Curly braces contain the declarations that belong to a CSS rule.

Can one CSS rule contain multiple declarations?

Yes. A declaration block can contain multiple property-value pairs.

Can a stylesheet contain multiple CSS rules?

Yes. Real stylesheets normally contain many rules.

How do I write a CSS comment?

Write CSS comments between /* and */.

Can I use // for CSS comments?

No. Standard CSS comments use /* ... */.

Does whitespace matter in CSS?

CSS allows flexible whitespace in many places, but consistent formatting improves readability.

Can CSS be written on one line?

Yes, but readable multi-line formatting is usually better during development.

What happens when CSS syntax is invalid?

The browser usually ignores the invalid declaration or rule portion that it cannot understand and continues processing.

Does one CSS error break the entire stylesheet?

Not always. Browsers are designed to recover from many errors and continue parsing later CSS.

Why is my CSS declaration ignored?

Possible reasons include invalid syntax, an unknown property, an invalid value, selector mismatch, or another declaration winning in the cascade.

What is the difference between invalid and overridden CSS?

Invalid CSS cannot be correctly parsed or used, while overridden CSS may be valid but loses to another declaration in the cascade.

How can I find CSS syntax errors?

Use syntax highlighting, editor warnings, browser developer tools, and CSS validation tools.

Should I write one declaration per line?

It is a common development practice because it improves readability and maintenance.

What should I learn after CSS syntax?

The next important topic is CSS selectors, which determine exactly which HTML elements receive styles.

Key Takeaways

  • CSS syntax defines how CSS code is written.
  • A CSS rule normally contains a selector and declaration block.
  • The selector identifies the elements to style.
  • The declaration block is enclosed in curly braces.
  • A declaration block can contain one or more declarations.
  • A declaration contains a property and value.
  • The property identifies what should change.
  • The value defines the setting to use.
  • A colon separates the property from its value.
  • A semicolon ends a declaration.
  • An opening curly brace starts a declaration block.
  • A closing curly brace ends a declaration block.
  • One CSS rule can contain multiple declarations.
  • A stylesheet can contain multiple CSS rules.
  • One selector can match multiple HTML elements.
  • Different rules can target different elements.
  • CSS comments use /* ... */.
  • HTML comment syntax should not be used for normal CSS comments.
  • Standard CSS does not use // comments.
  • Whitespace is flexible in many parts of CSS.
  • Readable formatting is better for development.
  • One declaration per line improves readability.
  • Consistent indentation makes stylesheets easier to maintain.
  • Invalid declarations may be ignored by the browser.
  • One invalid declaration does not necessarily break the entire stylesheet.
  • Valid declarations may continue to work after an invalid declaration.
  • A valid declaration can still be overridden by the cascade.
  • Invalid and overridden CSS are different problems.
  • Developer tools help identify CSS problems.
  • Correct syntax is required for advanced CSS topics.
  • Selectors, colors, layouts, transitions, and animations all depend on CSS syntax.
  • Understanding CSS syntax makes debugging easier.
  • Readable CSS is easier to maintain.
  • Correct punctuation is important.
  • Property names must be spelled correctly.
  • Values must be valid for their properties.
  • CSS syntax is the foundation of writing stylesheets.

Summary

CSS syntax defines the structure used to write styling rules.

A standard CSS rule contains a selector followed by a declaration block.

The selector identifies which HTML elements should receive the styles.

The declaration block is placed inside curly braces and contains one or more declarations.

Each declaration contains a property and a value.

The property identifies what should change, while the value defines the setting that should be used.

A colon separates the property from its value, and a semicolon ends the declaration.

A single CSS rule can contain multiple declarations, and a stylesheet can contain many different rules.

CSS comments use the /* ... */ syntax and are ignored by the browser when styles are applied.

Although CSS allows flexible whitespace, readable formatting and consistent indentation make stylesheets easier to understand and maintain.

When the browser finds invalid CSS, it often ignores the declaration it cannot understand and continues processing the remaining code.

Learning correct CSS syntax gives you the foundation required for every topic that follows.

In the next lesson, you will learn CSS selectors and discover the different ways to target specific HTML elements.