Syntax of CSS
CSS follows a rule-based structure. Each rule consists of a selector and a declaration block. Each CSS rule comprises a selector and a declaration block, where selectors identify the HTML elements to style, and declaration blocks define the properties and their corresponding values.
General Syntax of CSS
selector {
property: value;
}
Key Elements of CSS Syntax
- Selector: Specifies the HTML element(s) to target (e.g., h2, .class-name, #id-name).
- Declaration Block: Enclosed within curly braces {} and contains one or more property-value pairs.
- Property: Defines the style attribute to modify (e.g., color, background-color).
- Value: Sets the specific style for the property (e.g., blue, 5px).
- Semicolon (;): A critical component, required at the end of each property-value pair to separate multiple declarations within a block.
Example: Single Property Declaration
h2 {
color: blue;
}
Within the declaration block, there can be multiple pairs of properties and values.
Example: Multiple Property Declarations
button {
color: white;
background-color: black;
border: transparent;
border-radius: 5px;
}
Here, button is the selector, and there are multiple pairs of properties and values. Each pair is separated by a semicolon ;
.
Best Practices
- Always include a semicolon (;) after each property-value pair, even if it’s the last declaration in the block, to maintain consistency and avoid errors when adding new styles.
- Use clear and descriptive property names and values to enhance code readability and maintainability.