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;
}
- Selector – selects the HTML element
- Property – defines what you want to style
- Value – specifies how the property should look
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
- Each declaration must end with a semicolon (;)
- Properties and values are separated by a colon (:)
- Declaration blocks are enclosed in curly braces { }
- CSS is generally written in lowercase for readability
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
- Forgetting semicolons
- Using incorrect property names
- Missing curly braces
- Writing invalid values