How to Organize Your CSS

Organizing my css styles does not come easily. I like to just throw styles on the page when I need them and then forget about them. If I need to edit the style I can always use a Find or Search function for the id, class or tag name I need.

If you are the only one working on your project you might be able to get away with just using the search function in your IDE. You probably know (generally) where things are because you put them there. But organization is still important.

The real power of organization comes when other people use and modify your css. If anyone other than yourself is going to even look at your stylesheet you have to make if accessible.

There might be a hundred ways to put your stylesheet together in a logical, readable way. Here is one way that works for me:

1. It goes without saying to get your style definitions out of your html document. Putting your styles in a <style> tag really only works for an extremely small project that will never grow. If you want to scale your project, having your html and css in one page gets ugly. As far as inline styles, I only use them occasionally when I am dynamically generating certain elements. I never use inline styles in static html.

2. Use /**/ comments to explain and segment your external stylesheet. At the beginning of the .css file it is convenient to have a comment block that describes how the style rules are organized and the stylesheet’s relationship to other stylesheets, if there are any.

Some developers like to put common block level element (body, header, footer, p, h1 …) styles on a sheet separate from all other css. Others have separate sheets for each type of page on their site. This should be documented at the top of each css file to make style navigation easier.

A lot of my work is done for single page GIS apps so I usually have a single external css page. In these cases I note that this is the only css stylesheet for the app.

3. Everyone has their own favorite way of laying out their styleswithing the stylesheet. Some organize their ids and classes alphabetically while others might order them parallel to their element’s order in the html. I find that it makes most sense to group styles according to sections of the page. Sometimes I put css blocks in order of how the html sections are created but this isn’t always the case. Within each of these sections I try to further order elements from top to bottom as they appear in the html.

There are a lot of ways to organize css and what I outlined above is only one of them. The most important thing is just to have some form of organization and then be consistent in applying it.