CSS Syntax
Learn the fundamental syntax of CSS, the language that brings style and design to your web pages.
The Anatomy of a CSS Rule
A CSS rule, or rule set, is the basic building block of any CSS stylesheet. It consists of a selector and a declaration block. The selector targets the HTML element you want to style, and the declaration block contains one or more declarations that define the styles.
/* The basic structure of a CSS rule */ h1 { color: blue; /* A declaration */ font-size: 24px; /* Another declaration */ }
🔍 Components of a CSS Rule
- Selector: The `h1` in the example above. It points to the HTML element you want to style.
- Declaration Block: The code enclosed in curly braces `{...}`. It contains all the styling for the selector.
- Declaration: A single property and its value, like `color: blue;`.
- Property: The attribute you want to change, like `color`.
- Value: The specific value for the property, like `blue`.
Comments in CSS
Comments are an important part of writing clean and maintainable code. They are ignored by the browser but help developers understand the purpose of the code. CSS comments start with /*
and end with */
.
/* This is a single-line comment */ p { color: green; /* This is a comment next to a declaration */ } /* * This is a * multi-line * comment. */
Grouping Selectors
If you want to apply the same styles to multiple HTML elements, you can group the selectors by separating them with a comma. This is an efficient way to write less code and keep your stylesheet organized.
/* This rule styles both h1 and h2 elements */ h1, h2 { font-family: 'Inter', sans-serif; font-weight: 700; }
You can also group classes, IDs, or any other type of selector.
/* Apply same styles to 'success' and 'warning' classes */ .success, .warning { padding: 1rem; border-radius: 0.5rem; }
The Cascade and Specificity
The "C" in CSS stands for Cascading, which is the process of combining different stylesheets and resolving conflicts between them. When multiple rules apply to the same element, the browser uses a system called specificity to determine which rule's styles to apply. A more specific selector will always override a less specific one.
⚠️ Important!
Understanding specificity is key to mastering CSS. A selector's specificity is calculated based on the number and type of selectors used (e.g., ID selectors are more specific than class selectors, which are more specific than element selectors).