CSS Syntax
CSS syntax defines how CSS rules are written. A CSS rule normally consists of a selector followed by one or more declarations that describe how the selected HTML elements should be displayed.
Learning the basic structure of a CSS rule makes it easier to understand and write CSS throughout the rest of these tutorials.
CSS Rule
A CSS rule contains a selector and a declaration block. The selector identifies the HTML element or elements to style, while the declaration block contains the styles that are applied.
p {
color: blue;
}
In this example, p is the selector and color: blue; is the declaration.
The opening and closing curly braces contain the declaration block.
CSS Selector
The selector appears before the opening curly brace and tells the browser which HTML elements the CSS rule applies to.
p {
color: blue;
}
The p selector targets all <p> elements that match the rule.
CSS provides many types of selectors. Later tutorials cover element selectors, class selectors, ID selectors, attribute selectors, combinators, pseudo-classes, and other selector types.
CSS Declarations
A CSS declaration consists of a property and a value separated by a colon. The declaration normally ends with a semicolon.
color: blue;
In this declaration, color is the property and blue is the value.
The property identifies what aspect of the element will be styled, while the value specifies the setting that will be applied to that property.
Multiple CSS Declarations
A declaration block can contain multiple declarations. Each declaration is written on its own line and normally ends with a semicolon.
p {
color: blue;
font-size: 18px;
line-height: 1.5;
}
This rule applies three declarations to matching paragraph elements. The text is displayed in blue, the font size is set to 18 pixels, and the line height is set to 1.5 times the element's font size.
Although the semicolon after the final declaration can sometimes be omitted, including it is a good practice because it makes adding additional declarations easier and helps prevent syntax errors.
CSS Syntax Example
The following example uses a CSS rule to style a heading and another rule to style a paragraph.
<style>
h1 {
color: blue;
font-size: 32px;
}
p {
color: #333333;
font-size: 18px;
}
</style>
<h1>CSS Syntax</h1>
<p>CSS rules control how HTML elements are displayed.</p>
Play in Editor
The first rule selects the <h1> element and changes its text color and font size. The second rule selects the <p> element and applies a different text color and font size.
