CSS Syntax
CSS syntax follows a specific structure to define how elements on a web page should be styled. The syntax is the foundation of web page styling, resembles a recipe combining selectors and declarations or property & value pairs.
CSS Syntax Key Components:
1. CSS Selector:
- Specifies which HTML elements you want to style.
- Examples:
h1
,p
,.my-class
,#my-id
2. CSS Declaration Block:
- Encloses one or more declarations within curly braces
{}
. - Contains the specific styles to be applied to the selected elements.
3. CSS Declaration:
- Consists of a CSS property followed by a colon
:
and a value. - Sets a specific style aspect for the selected elements.
4. CSS Property:
- The name of the style characteristic you want to modify.
- Examples:
color
,font-size
,margin
,border
,background-color
5. CSS Value:
- Assigns a specific value to the property, determining the visual effect.
- Examples:
blue
,16px
,10px
,solid
,#f0f0f0
General CSS Syntax Structure:
CSS:
selector {
property-name: value;
property-name: value;
/* Additional declarations (property: value:) can be added here. */
}
CSS Syntax Example:
To style a paragraph HTML tag with CSS, craft a rule using the selector “p” as a target, followed by a declaration pairing a property (like “color” or “font-size”) with its desired value (e.g., “red” or “18px”), all embraced within curly braces.
CSS:
p {
color: red; /* Sets text color to red */
font-size: 18px; /* Sets font size to 18 pixels */
}
Additional Notes:
- Comments: Use
/* */
to add comments within CSS code for clarity and documentation. - Semicolons: Each declaration must end with a semicolon “
;
“, although some browsers might tolerate missing semicolons in isolated cases, it’s considered best practice to consistently use them. - Multiple Selectors: Separate multiple selectors with commas to apply the same styles to different elements.
- Specificity: The order of selectors and how specific they are determine which styles take precedence if multiple rules apply to the same element.
- Indentation: Not required for browsers to interpret CSS, but it’s essential for code readability and maintainability.
Now that you understand the CSS syntax, with the combination of selectors, declarations, properties, and values, get ready to style and watch your web page designs blossom from bare basics to masterpieces!