CSS Coding Standards

A collection of coding standards I use for CSS.

Linking

An external stylesheet should be embedded int he page using the link element, like:

<link rel="stylesheet" media="screen" type="text/css" href="http://www.klauskomenda.com/wp-content/themes/back2black/css-min-03102008.css">

Naming of classes and selectors

Always use lowercase characters with dashes. Examples:

.book-cover {
    ...
}

Browser Hacks

Avoid using browser hacks altogether, try to find a way around a certain problem by not having to use a hack. However, if they need to be used for Internet Explorer, use the Underscore Hack to target IE6 only:

.book-cover {
    _zoom: 1; /* trigger hasLayout it IE6 */
}

or the Star Hack to target IE6 and IE7:

.book-cover {
    *position: relative; /* fix rendering issue in IE6 and 7 */
}

Leave out quotes when giving a URL

When giving a URL to e.g. point to a background image in CSS, it is not necessary to put the URL in quotes. So instead of writing:

background:url("images/container_stripes_bg.gif");

you can write

background:url(images/container_stripes_bg.gif);

Conquer Doubled Float-Margin Bug

Whe you have floated elemenst and you are applying a margin in the same direction as the float, this will trigger the IE5/6 Doubled Float-Margin Bug. To fix this, always place a display: inline in the ruleset. Example:

.book-cover {
    float: left;
    width: 150px;
    height: 150px;
    margin: 5px 0 5px 100px;
    display: inline;
}

Outline

Do not set the outline to none, as this will have impacts on the accessibility of the page. If you set it to none because you would want to get rid of the dotted border when clicking on an image replaced element, use overflow: hidden instead.

Shorthand Notation

Where possible/valid, use shorthand notation for properties. Examples:

Font

font: small/18px "Lucida Grande", "Trebuchet MS", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif;

Background

background: transparent url(/i04/wrapinner.gif) top left repeat-y;

If you are not overriding a set property from another selector, you can also omit stating the default values again, which are:

  • background-color: transparent
  • background-image: none
  • background-repeat: repeat
  • background-attachment: scroll
  • background-position: 0% 0& (equal to ‘top left’)

Borders

border: 1px solid red;

Margin and Padding

The following examples apply likewise to padding.

margin: 1px 5px 2px 4px; /* clockwise, starting from top */
margin: 10px 2px 5px /* top | sides | bottom */
margin: 10px 5px /* top, bottom | left, right */

List-style

list-style:square inside url(image.png);

Colors

Color declarations can be shortened if the value for all three properties (R, G and B) are the same. So the following

color: #AAAAAA;

should be shortened to:

color: #aaa;

Switch to our mobile site