CSS Syntax
CSS Syntax
Section titled “CSS Syntax”Understanding the basic structure of CSS rules.The Structure of a CSS Rule
Section titled “The Structure of a CSS Rule”A fundamental CSS unit is the rule set. Each rule set consists of two main parts:
- Selector: Targets the HTML element(s) you want to style.
- Declaration Block: Contains one or more style declarations, enclosed in curly braces
{}.
Visualizing the parts:
Selector { Declaration Block }
Inside the Declaration Block:
Section titled “Inside the Declaration Block:”Each declaration includes:
- A Property: The style attribute you want to change (e.g.,
color,font-size,margin). - A Value: The specific setting for that property (e.g.,
red,16px,10px).
The property and value are separated by a colon (:).
Each declaration within a block must end with a semicolon (;). This semicolon separates multiple declarations.
Visualizing a declaration:
property: value;
CSS Example Explained
Section titled “CSS Example Explained”Let’s look at a complete CSS rule set:
p { color: red; text-align: center;}Breaking it down:
pis the selector. It targets all<p>(paragraph) elements.{ ... }encloses the declaration block.color: red;is the first declaration.-
coloris the property.
-
redis the value.
-
;is the semicolon separating it from the next declaration.
text-align: center;is the second declaration.-
text-alignis the property.
-
centeris the value.
-
;is the semicolon ending the declaration (and the block, in this case).
This rule set tells the browser to make all paragraph text red and center-aligned.
Readability: While you can write CSS on a single line (p {color:red; text-align:center;}), putting each declaration on its own line, indented within the curly braces, is standard practice and makes the code much easier to read and maintain.
CSS Comments
Section titled “CSS Comments”Comments are used to explain your code for yourself or other developers. They are completely ignored by the browser.
CSS comments start with /* and end with */. They can span multiple lines.
/* This is a single-line comment */p { color: blue; /* Set the text color */ font-size: 16px;}
/* This is a multi-line comment. It explains the purpose of the following rule.*/.highlight { background-color: yellow;}Use comments to document complex sections, explain non-obvious choices, or temporarily disable code (‘commenting out’).