CSS Syntax
Learn the fundamental structure and rules of CSS code
Basic CSS Syntax
CSS syntax consists of a selector and a declaration block. The selector points to the HTML element you want to style, and the declaration block contains one or more declarations separated by semicolons.
Basic Syntax Structure:
selector {
property: value;
property: value;
}
/* Example */
h1 {
color: blue;
font-size: 24px;
text-align: center;
}
CSS Rule Components:
- Selector: Points to the HTML element to style (e.g., h1, .class, #id)
- Declaration Block: Contains style declarations inside curly braces {}
- Property: The style attribute you want to change (e.g., color, font-size)
- Value: The setting you want to apply to the property
- Semicolon: Separates multiple declarations
Multiple Selectors
Grouping Selectors:
/* Apply same styles to multiple elements */
h1, h2, h3 {
color: navy;
font-family: Arial, sans-serif;
}
/* Target specific elements */
.header h1,
.main-title,
#site-title {
font-size: 32px;
margin-bottom: 20px;
}
Comments in CSS
Adding Comments:
/* This is a single-line comment */
/* This is a
multi-line comment */
h1 {
color: blue; /* Set text color to blue */
font-size: 24px; /* Define font size */
}
CSS Values and Units
Common Value Types:
/* Numbers */
p {
line-height: 1.6; /* No unit */
padding: 10px; /* Pixels */
margin: 2em; /* Em units */
width: 50%; /* Percentage */
}
/* Colors */
.element {
color: red; /* Named color */
background: #ff0000; /* Hexadecimal */
border-color: rgb(255, 0, 0); /* RGB */
outline-color: rgba(255, 0, 0, 0.5); /* RGBA with opacity */
}
/* Text Values */
.text {
font-family: Arial, sans-serif; /* Font names */
text-align: center; /* Keyword value */
font-style: italic; /* Keyword value */
}
CSS Property Values
Value Categories:
- Keywords: center, left, right, none, auto
- Length Units: px, em, rem, vh, vw
- Colors: named colors, hex, rgb(), hsl()
- Numbers: integers or decimals
- Percentages: relative to parent element
- Functions: rgb(), url(), calc()
Common Mistakes to Avoid
Incorrect vs Correct Syntax:
/* ❌ Incorrect */
h1 {
color blue; /* Missing colon */
font-size: 24px /* Missing semicolon */
text-align:center /* Missing semicolon */
}
/* ✅ Correct */
h1 {
color: blue;
font-size: 24px;
text-align: center;
}
Common Errors:
- Missing colons (:) after property names
- Omitting semicolons (;) at the end of declarations
- Using invalid property names or values
- Incorrectly nesting CSS rules