CSS Syntax
CSS syntax is the foundation of writing CSS code to style HTML elements. Understanding how to correctly structure your CSS rules is key to applying styles effectively to web pages.
CSS Rule Structure
A CSS rule is made up of two main parts: the selector and the declaration block.
selector {
property: value;
}
Here’s a breakdown of the structure:
- Selector: Specifies the HTML element that you want to style (e.g., <h1>, <p>, <div>).
- Property: The style attribute that defines what aspect of the element you are modifying (e.g., color, font-size, margin).
- Value: The value you want to assign to the property (e.g., red, 16px, #ff5733).
Example of CSS Syntax
Here’s a simple CSS rule that changes the text color and font size of all <h1> elements:
h1 {
color: red;
font-size: 36px;
}
This rule targets all <h1> elements and sets their text color to red and font size to 36px.
Multiple CSS Declarations
A CSS rule can contain multiple declarations separated by a semicolon. Each declaration consists of a property and value pair.
h1 {
color: red;
font-size: 36px;
margin-bottom: 20px;
}
This rule sets the color, font size, and margin of all <h1> elements at once.
Types of Selectors
CSS selectors are used to target HTML elements for styling. There are different types of selectors:
- Universal Selector: The universal selector (
*
) selects all elements in the document.
* {
color: blue;
}
p { color: green; }
.
). Example: .my-class { color: purple; }
.my-class {
color: purple;
}
#
). Example: #header { font-size: 24px; }
#header {
font-size: 24px;
}
input[type="text"] { border: 1px solid black; }
input[type="text"] {
border: 1px solid black;
}
CSS Comments
You can add comments in your CSS code to explain your styles. Comments are ignored by the browser and do not affect the page rendering:
/* This is a comment */
h1 {
color: red; /* This changes the color of h1 elements */
}
Use comments to keep your code organized and easier to understand for you or other developers.
Best Practices for CSS Syntax
- Be consistent: Stick to a consistent naming convention and style structure for your selectors and properties.
- Use indentation: Proper indentation makes your CSS code readable and maintainable.
- Group related rules: Try to group related CSS rules together in a logical manner to keep your stylesheet organized.
- Avoid unnecessary properties: Only apply the styles you need to avoid cluttering your CSS.
Example of CSS Syntax for a <div> Element
This example shows how to apply multiple CSS properties to a <div> element:
div {
background-color: #f4f4f4;
padding: 20px;
border: 2px solid #ccc;
border-radius: 10px;
width: 300px;
}
This will apply a light gray background, 20px padding, a border, rounded corners, and set the width of the <div> element.