CSS syntax is the set of rules browsers use to interpret stylesheets. It consists of rule sets, each containing a selector and a declaration block.
/* This is a comment in CSS */
p { /* 'p' is the selector, targeting all paragraph elements */
color: blue; /* 'color' is the property, 'blue' is the value */
font-size: 16px; /* 'font-size' is the property, '16px' is the value */
}
Explanation The example demonstrates a CSS rule targeting all <p>
(paragraph) elements. It sets their text color
to blue and font-size
to 16 pixels. Each declaration ends with a semicolon.
Selectors (Type, Class, ID, Universal, Grouping)
CSS selectors are patterns used to select the HTML elements you want to style. They specify which elements a CSS rule applies to.
Example 1: Type Selector
/* Selects all <h1> elements */
h1 {
color: #333; /* Sets the text color to a dark gray */
}
Explanation This CSS rule uses a type selector to target and style all instances of the <h1>
HTML element, setting their text color.
Example 2: Class Selector
/* Selects all elements with the class "highlight" */
.highlight {
background-color: yellow; /* Sets the background color to yellow */
font-weight: bold; /* Makes the text bold */
}
Explanation The .highlight
class selector styles any HTML element that has the class="highlight"
attribute, making its background yellow and text bold.
Example 3: ID Selector
/* Selects the element with the ID "main-header" */
#main-header {
text-align: center; /* Centers the text */
}
Explanation The #main-header
ID selector uniquely targets a single HTML element with id="main-header"
, typically used for distinct page elements.
Example 4: Universal Selector
/* Selects all elements on the page */
* {
margin: 0; /* Resets default outer spacing for all elements */
padding: 0; /* Resets default inner spacing for all elements */
}
Explanation The *
universal selector applies the defined styles to every single element within the HTML document, often used for global resets.
Example 5: Grouping Selector
/* Selects all <h1>, <h2>, and <h3> elements */
h1, h2, h3 {
font-family: Arial, sans-serif; /* Sets a common font family */
}
Explanation The grouping selector h1, h2, h3
applies the same font family style to all <h1>
, <h2>
, and <h3>
elements, promoting consistent typography.