CSS

2.3 Syntax, Rules, Comments

Contents

Syntax Formatting

There are several basic CSS syntax requirements to keep in mind:

  1. Always use curly brackets around your declarations.
  2. Separate properties and values with a colon.
  3. End your declarations with a semicolon.
  4. Put declarations on separate lines. This is the prefered way‚ see exmaple below.
  5. CSS rules can be written with or without spaces between properties and values. Choose one way and stick with it.
  6. The industry standard is to indent declarations (as in the example below).


selector{
    property:value;
    property:value;
}

Rules

Aside from the syntax guidlines above, there is only one other rule to remember: CSS selectors and properties cannot have spaces. If the name of a CSS property has more than one word, the words must be hyphenated.

Examples: background-color, font-size, font-family

Error Checking

If you make a mistake in your CSS, you will not be alerted in any way by the text editor, browser, or anything else. In some cases the page, element, or content may still show up just fine. In other cases, it may not.

If something is not working or displaying properly, check:

  1. The selector
  2. The selector before the affected one
  3. Your colons and semicolons
  4. Your curly brackets

Comments

Comments in CSS are used to insert notes in the CSS source code. They are visible to anyone that views the page source code, but are not shown in the browser.

To write a comment, enclose the text with an asterisk and a forward slash on each side, like this:

/* this is a comment in CSS */



h1{
    color:blue;
    /* this is a comment, along with the two lines below
    font-weight:bold;
    font-style:italic; */
}

Shorthand

There are some CSS properties that can be combined into one. Using shorthand properties can save time and make your CSS style rules shorter and easier to read. For example:



  border-width:5px;
  border-style:solid;
  border-color:black;

Can be written as:



border:5px solid black;

This also works for font, padding, margin, and others.

Multiple Selectors

If you would like to change the properties on more than one selector you can use this syntax:



h1,h2,p{
  color:red;
}	

This will change the color of the <h1> and the <h2> and the <p> at the same time.

Display

In HTML, elements are one of two types — either block or inline elements (see Section 1.3: Block vs. Inline). You can change the element type using the display property:



h1{
  display:inline;
}	

This will change the h1 from a block element to an inline element and the headlines will no longer appear on new lines or stretch out to take up all the space. Alternately, you can change an inline element to a block element by using display:block; Change the display property sparingly.