Thursday, 8 July 2010

Quick CSS tip - alphabetise your properties

Since I first read about this technique about a year ago I've been using it without even thinking about, but I'm reminded how much of a time saver it is every time I work with CSS that isn't alphabetised.

Compare and contrast:

Unordered properties

.myclass {
    position:absolute;
    top:0;
    left:0;
    width:42%;
    margin:0 0 0 8px;
    padding:8px 10px 10px 10px;
    border:1px solid #e6e6e6;
    background:#f5f5f5;
    visibility:hidden;
    font-size:85%;
}


Properties in alphabetical order

.myclass {
    background:#f5f5f5;

    border:1px solid #e6e6e6;
    font-size:85%;   
    left:0;
    margin:0 0 0 8px;
    padding:8px 10px 10px 10px;
    position:absolute;
    top:0;
    visibility:hidden;
    width:42%;   
}



Image by Jan Tik

3 comments:

  1. While I agree that a consistent way of ordering CSS properties is better than no ordering at all, I don't think alphabetical is the best way.

    Alphabetical ordering makes it much harder to understand the overall effect of the rule, since related properties don't sit together (e.g. width and height are far apart). This also speeds up authoring, as you tend to write related properties in chunks (width then height, top then left, margin then padding, etc.)

    The scheme we follow at Isotoma is based on how Firebug orders CSS properties in the "Show computed styles" view:

    1. Layout declarations (position, float, clear, display, visibility, etc.);
    2. Box Model declarations (top, right, bottom, left, width, height, margin, padding, border);
    3. Background declarations;
    4. Text declarations (font, color, line-height, text-transform, text-decoration, text-align, etc.);

    ReplyDelete
  2. I do agree that separating related properties like width and height is a downside, and that grouping related properties is good idea. As you say, Firebug groups them this way in the "Show computer styles" view.

    However, under the "Style" view (which I'm looking at 99% of the time when I'm using Firebug), it alphabetises them instead of grouping them.

    I spend a lot of time switching between Firebug and my text editor, so I find it much easier if the properties appear in the same order in both places.

    ReplyDelete
  3. I too have adopted an alphabetical ordering of my CSS attributes as it does make it easier to read.

    Though Francois does make a good argument for grouping attributes by layout, box model, background and text, unfortunately not all the 'back-end developers' who work with the 'front-end developers' on projects understand these more abstract groupings. They know the ins-and-outs of Java, but not the complexities of CSS. Multi- cross-disciplinary developments are where these groupings fall-down.

    That said, alphabetical ordering isn't perfect. CSS hacks for example don't always allow alphabetical ordering due to quirks in the browsers.

    ReplyDelete