Each CSS rule consists of a selector that identifies the HTML elements to be styled, and one or more declarations that specify which style to apply to those elements.
Per CSS syntax, the number of declarations in a CSS rule determines whether semicolons are required or not.
Adjacent declarations in a CSS rule are separated by a semicolon. If a CSS rule consists of only one declaration, a semicolon is not required. A semicolon also isn’t required after the last declaration in a multi-declaration CSS rule.
This applies to all CSS code, whether it’s inlined in the style=""
attribute of your HTML document’s elements, embedded in a <style> tag in the document’s <head>
section, or externally hosted and linked to in a <link rel="stylesheet">
tag.
Single-declaration CSS rules
The following CSS rule, which gives all <h1>
elements a font size of 42 pixels, has one declaration:
Since this CSS rule contains only one declaration, no semicolon is required after its end—that is, there’s nothing to separate it from.
Multi-declaration CSS rules
Add a second declaration to this CSS rule, and the situation changes.
Now, a semicolon is required between the first and the second declaration. It acts as the separator that tells the browser that these are two different declarations as it parses the HTML document’s CSS style sheet.
Note, however, that there’s no semicolon at the end of the last declaration.
Remember that the semicolon is required to separate pairs of adjacent declarations. In other words, it’s never needed after the last declaration in a CSS rule because that rule isn’t part of a pair (at least to the right).