You already know that a CSS style sheet is a collection of styles or style rules. Each rule defines how one or more HTML elements should be displayed. In this lesson you’ll see how to write a CSS style rule (or, CSS syntax).
Anatomy of a CSS style rule
In its simplest form, a CSS style rule has two parts –
- A Selector: A selector selects HTML element(s) to which the style rule will be applied. A selector could be one or more HTML element(s). Example of selectors are heading elements (h1, h2 …), a paragraph element (p) etc.
- A Declaration: After selecting the element(s) by the selector, the declaration portion declares how the selected element will look like. A declaration is a property-value pair. Property and value are separated by a colon (:) and terminated with a semicolon. A declaration is surrounded by an opening curly brace and a closing curly brace.
A declaration has two parts-
- A property: A property is a predefined CSS specification that tells which sort of formatting will be applied on the selector. A property is a one word or a few-hyphened word and they are very intuitive. Most of the times, the names tell what it does. For example, “font-size” property defines the size of the font. Similarly, “background-color” which defines background color etc. You’ll learn different properties throughout this course.
- A value: a value is the value of a property. For some properties, it is one from a defined list of values and for the remaining, it is a custom defined value.
You’re not limited to one declaration in a single syntax rule. You can add as many declarations as you need.
CSS style rule examples
(a) Single declaration: The following style rule is for setting paragraph text color as Corn Flower Blue. Here color is the property and #3498db is its value which is the hexadecimal representation of Corn Flower Blue.
(b) Multiple declarations: The following style rule has two declarations. It set the text color as #3498db and font size as 12 pixels.
Dos of CSS style rule
- Use lowercase as the property name.
- To understand style rules easily, indent each property with a tab or a couple of spaces. Browsers will ignore those spaces; so, add as much indent that will make your code more readable. Whatever you use, stick with that spacing scheme. See the following example-
- It is a good practice to always use semicolon after each declaration even it is the only pair.
Don’ts of CSS style rule
- Don’t omit colon between the property and the value.
- Don’t omit the opening or closing curly braces.
- If there is more than one declaration for a rule, then, don’t omit the semicolon after each declaration. Though, you can leave the last semicolon.
Now, as you’ve seen how to how to write CSS rules, the next step is how to attach the style rules to the HTML. In the next lesson Adding CSS to HTML, you’ll see how to add CSS to a web page.