Login | Contact Us | Site Map | Resources

Introduction to CSS

Home > CSS Tutorial > CSS Syntax

CSS Syntax

The CSS syntax is a set of rules that define how CSS should be written. CSS is, in that sense, no different from any other language. If I wrote this sentence backward and upside down, it would not be following the rules, and it is doubtful that anyone would understand it. When a web browser reads CSS code, it expects certain rules to be followed so that it can know what to do with what it is reading.

Although there are three different ways that CSS can be applied to an HTML document, the basic syntax is the same. That syntax is:

selector { property: value; }

The "selector" will specify which HTML element that the style will apply to. For example:

p { property: value; }

The "p" is an HTML element meaning "paragraph", so this selector value will apply to all paragraph elements found in the HTML file.

The "property" will specify which attribute of style that you want to change. For example:

p { border: value; }

The "property" is now set to "border", meaning that we are telling the browser that we want all of our paragraphs to have a border. The "value" will tell the browser what type of border that we want. For example:

p { border: 1px dotted #000000; }

This example, when translated to plain English, would say: "I want all my paragraphs to have a border! I want this border to be a dotted black line that is 1 pixel in size on all four sides!". CSS values are demanding little things, aren't they?

In CSS, multiple declarations can be made, and whitespace is ignored, so the following two examples mean the exact same thing to the browser:

p { margin: 0; border: 1px dotted #000000; }

p {
    margin: 0;
    border: 1px dotted #000000;
}

CSS allows selectors to be grouped together (comma separated) if the same style applies to them all, as shown in the following example, which specifies that all text inside of these HTML elements should be green:

p, h1, h2 { color: green; }

It is important to note that a full colon is used to separate the property from the value, and a semicolon is used to express the end of the value, or declaration. The braces { & } are also necessary to determine which declarations apply to which selector. If any of these are forgotten, mysterious things may happen... or they may not. You'll have to try it and see.