CSS Syntax
The syntax of CSS is very intuitive and easy to understand. It consists of a series of Rulesets, where each ruleset defines how to style one or more HTML elements.
Structure of a Ruleset
A basic CSS ruleset consists of two parts:
- Selector: It "selects" the HTML element(s) you want to style.
- Declaration Block: It contains one or more Declarations separated by semicolons.
css
/* This is a CSS ruleset */
h1 {
color: blue;
font-size: 24px;
}Let's break down this example:
h1is the Selector. It points to all<h1>elements on the page.{ ... }The curly braces and everything inside them constitute the Declaration Block.color: blue;is a Declaration. It consists of a Property and a Value.coloris the Property.blueis the Value.
font-size: 24px;is another Declaration.
To summarize:
- You use a Selector to target HTML elements.
- Then, inside the Declaration Block, you specify a Value for the Properties of these elements.
- Each declaration must end with a semicolon (
;). - The entire declaration block must be enclosed in curly braces (
{}).
CSS Comments
Like all programming languages, you can add comments in CSS to explain your code, mark sections, or temporarily disable certain code. CSS comments start with /* and end with */.
css
/* This is a single-line comment */
p {
color: green;
}
/*
This is a
multi-line comment.
The rule below would make all paragraphs red,
but it is commented out, so it won't take effect.
*/
/*
p {
color: red;
}
*/Comments are very important for code maintenance and team collaboration.
Syntax Key Points
- Case Insensitivity: CSS syntax is generally case-insensitive. However, when it involves filenames or URLs (such as font names, background image paths), it is usually case-sensitive. To maintain consistency, it is recommended to always use lowercase letters when writing CSS.
- Whitespace: Spaces, tabs, and newlines are generally ignored in CSS. You can use them to format your code and improve readability.
For example, the following two ways of writing are equivalent, but the first one is obviously easier to read:
css
/* Recommended style */
body {
font-family: Arial, sans-serif;
line-height: 1.5;
}
/* Not recommended style */
body{font-family:Arial,sans-serif;line-height:1.5;}Having mastered the basic syntax structure, you can now start learning the most powerful and core part of CSS—Selectors.