Some Practical Guidelines For Writing CSS

Do you follow a consistent set of practices when writing your css or do you write a few lines of css that work before move on to the next line? Did your best practices grow organically or did you follow a set of guidelines for writing your code?

For a number of weeks, I’ve been looking at my own css practices and considering a variety of new ideas for formatting and combining css and html. A few weeks back in an article about css formatting I received a couple of comments pointing me to additional resources and ideas.

Last week I looked at a presentation about DRY CSS Brett pointed me to and this week I want to look at article David pointed me to that offers guidelines for writing css.

Occupy DC guidelines written on a piece of cardboard

Some General CSS Guidelines

These css guidelines come from the folks at CSS Wizardry. I don’t want to repeat the entirety of their article here. Instead I’ll offer a few highlights and encourage you to check them out in full on Github.

You can also find an example of a stylesheet following these guidelines here.

They advise beginning each file with a table of contents that’s mapped to the different sections of the file. I’ve always wondered how useful these are since you still need to scroll the file to see anything, but I suppose a quick overview at the top can be helpful.

1
2
3
4
5
6
7
8
9
10
/* ------------------------------- *\
             Contents 
\* ---- -------------------------- */
/*
Reset
Base
Layout
Modules
Navigation
*/

They also suggest using a prefix for each section so they begin each section with a comment in the form of $[section name] in order to make searching quicker. Since only the section heads will have the prefix a search will take you right to the section, which is an interesting idea as the file can’t link directly to its parts.

1
2
3
/* ------------------------------- *\
             $Layout
\* ---- -------------------------- */

Bitmapped text spelling 'syntax error'

Syntax and Formatting

When it comes to syntax and formatting a number of ideas are presented.

  • Always use multi-line, which helps with version control. This was also pointed out to me in the comments of my post on css formatting.
  • Properties should ordered by relevance and not by the alphabet.
  • Use dashes instead of underscores or camelCase
  • Always include the trailing semi-colon
  • Comment as much and as often as possible, including commented markup to give context to a block of css
  • Indent your css to match how your html is nested. With vendor prefixes align along the colon:

I’m hesitant to want to comment everything as I think it can go too far and make it more difficult to scan a css file, however most of us don’t comment enough and the idea to add commented markup is interesting.

Another interesting guideline was to avoid using the shorthand property. The idea is that a shorthand essentially overwrites default values on what’s not included and you often want to keep these defaults. For example if you only want the margin-top to be 0 then say that instead of margin: 0, which also sets the left, right, and bottom values.

Ultimately you want to make sure the shorthand is really what you want before using it. In my own coding I typically start by writing the individual property, but once a couple of individual properties are present I’ll convert them to the shorthand.

2-column layout with header and footer and 3 modules in the sidebar on right

Components and Layout

They suggest writing your markup before your css when building new components. This allows you to visually see where css properties can be inherited and to stay in an OOCSS or DRY frame of mind when creating components. Ideally you’d identify visual patterns and build base objects for them. Then extend these objects with classes.

I can’t say I write all my html before getting to the css. I have a tendency to write the general layout markup getting containers for footers, content, asides, footers, etc, set and then writing the css to generate the basic layout. Then I go back and start filling in the containers and styling each before moving on to what’s inside the next container.

For layout you should keep components and modules free of widths and heights. Let your modules get their size from the underlying grid system layout. This allows components to remain fluid. For measurements use % for layout (widths) and rems for font size. Keep line heights unitless. I’m not 100% sure if rems are prime time ready yet, but if they are then yes this is the way to go.

This makes a lot of sense. Relative measurements are best for flexible layouts and I like the idea of setting these measurements on the basic layout as opposed to individual components, which we often want to be 100% of their containers anyway. By not setting widths and heights on everything we allow our design to better reshape itself under different conditions.

Jukebox selector

Selectors

A few guidelines about selectors, which should be familiar to you by now if you’ve been reading some of my recent posts.

  • Keep selectors efficient and portable
  • Avoid location based selectors as they lead to tighter coupling in html and css
  • Longer selectors likely have performance issues. Keep your selectors shorter

Avoid overqualified selectors as a class name usually enough. You generally don’t need to include the element in front.

1
.classname { }

is better than

1
div.classname { }

It’s usually better to place a class on the element you want styled instead of on containing elements and then drilling down to the element you want to style.

1
2
3
4
5
6
7
<nav>
  <ul>
    <li><a href=""></a></li>
    <li><a href=""></a></li>
    <li><a href=""></a></li>
  </ul>
</nav>

If you want to style the links above add the class to the links as opposed to adding one to the nav element and then digging down to the links. The former will keep your selector shorter and help it be more efficient and more portable.

Speaking of class names, they’re neither semantic nor unsemantic, something we’ve seen before. Class names are sensible or insensible.

Stay away from IDs for css. Add them to your html for Javascript (behavioral) hooks only and use classes for the styling hooks. It’s ok, however, to use !important when you absolutely know the rule should take precedence.

Lightbulb laying on a notebook of ideas

Additional Ideas

A few other ideas I found interesting

  • Avoid magic numbers and absolute values since they rarely work beyond the one special case
  • Avoid conditional stylesheets for IE
  • When debugging remove code before adding more

I’m not sure I follow the logic for the conditional comments guideline. Until more people are on IE9 and beyond I think our best bet for getting things to work on some older versions is to use conditional comments.

I know they’ve always had some controversy around them, but they’ve also seemed the most workable solution to me. You generally don’t need to use a lot of conditional comments or have them point to a lot of IE specific code, but they often help. Having said that I can’t say I’ve needed to use them as much in the last couple of years.

In regards to debugging, when something isn’t working as you expect, the problem is likely in the code already written and not in the code yet to be written. It makes sense to first remove what’s causing the problem and then rebuild your css instead of just adding more css on top of the problem. The latter will only lead to specificity nightmares.

Some nested css for navigation from the CSS Wizardry guidelines example

Summary

While I don’t necessarily agree with each and every one of these guidelines, I think they’re mostly right on track and make for good practice.

By following them, the developers at CSS Wizardry suggest the need for css preprocessors will be reduced, though it’s certainly ok to use preprocessor as extensions of above. They shouldn’t be used as an alternative, however. I don’t think these guidelines would eliminate the need for preprocessors, but I can see how they can help.

What do you think of these guidelines? Agree with them? Disagree? What additional guidelines do you use when writing css?

Download a free sample from my book, Design Fundamentals.

3 comments

  1. Thanks for the post. This was like a good reminder. I have been following most of the guidelines already, thanks to the experts like you sharing their knowledge.

  2. i really hate ordering css-properties by relevance. who came up with this?

    every human being intuitively expects a list to be ordered alphabetically (because most lists they’ve seen in their life where ordered either numerically or alphabetically).

    why do programmers have to come up with something nebulously like ‘relevance’? what is relevant? relevance is subject to interpretation.

    just order your properties alphabetically and EVERY CODER will intuitively understand the order.

    • I can understand your preference for alphabetical ordering. I think the reason relevance comes up is because certain css properties make sense together, but wouldn’t appear next to each other alphabetically.

      For example width and height or font-size and line-height. If you’re looking to change one, you might very well want to change the other, so having them closer together makes sense.

      I’m not saying relevance is the best way to organize properties, but I do think there’s a valid reason for wanting to do so.

Leave a Reply

Your email address will not be published.

css.php