CSS Syntax
What is CSS Syntax?
CSS syntax is the structure used to write CSS rules. A CSS rule tells the browser which HTML element to style and what styles should be applied to it.
Basic CSS Syntax Structure
A CSS rule consists of a selector and a declaration block. The selector targets the HTML element, while the declaration block contains one or more property-value pairs.
selector {
property: value;
property: value;
}
Parts of a CSS Rule
- Selector: Specifies the HTML element to style.
- Property: Defines the style feature to change.
- Value: Sets the value for the property.
- Declaration: A property and value pair.
- Declaration Block: A group of declarations enclosed in curly braces.
Example of CSS Syntax
h1 {
color: blue;
font-size: 36px;
text-align: center;
}
Explanation of the Example
- h1 is the selector.
- color is the property.
- blue is the value assigned to the color property.
- font-size sets the size of the text.
- text-align centers the heading.
Multiple CSS Declarations
A single selector can contain multiple declarations. Each declaration must end with a semicolon (;), except the last declaration where it is optional but recommended.
p {
color: #333;
font-size: 18px;
line-height: 1.6;
margin-bottom: 15px;
}
CSS Syntax Rules
- Selectors are followed by curly braces { }.
- Each declaration contains a property and a value separated by a colon :.
- Declarations end with a semicolon ;.
- Property names are case-insensitive, but lowercase is recommended.
- Spaces and indentation improve readability.
Common Syntax Mistakes
Complete CSS Syntax Example
body {
font-family: Arial, sans-serif;
background-color: #f8f9fa;
}
h1 {
color: #0d6efd;
}
p {
color: #444;
font-size: 18px;
}
Best Practices
- Always end declarations with a semicolon.
- Use proper indentation for readability.
- Keep selectors simple and meaningful.
- Group related styles together.
- Use consistent formatting throughout your stylesheet.
Web Resources on CSS Syntax
1. MDN Web Docs : Introduction to CSS syntax declarations, rulesets, and statements
2. Dev.to : CSS Syntax and Rules Selectors, Declarations, Properties, and Values
3. MDN Web Docs : CSS syntax
🧪 Test Your CSS Code
Edit the CSS code on the left and click “Run Code” to see the result on the right.
Click “Run Code” to see the result here.