CSS Table of Contents – Useful!

Stylesheets are those sort of files which often seem to get sloppy quite quickly. Compared to other files in a web project these perhaps don’t get much attention after the initial build. The temptation is to just make a quick edit, check your change works, then save and get out of there. Perhaps the problem is the lack of structure compared to a fully fledged application file.

Having an agreed style guide for how to write CSS is a good solution. Personally, I am a big fan of BEM-like naming conventions (check out this post by Nicolas Gallagher). An additional step I find useful is to create a table of contents for the stylesheet file.

Having a table of contents means:
* The file has a clear structure.
* As soon as the file is opened the table of contents is above the fold, getting the developer thinking straight away about where there code edit should be made — helping to avoid the ‘end-of-file-addition’ temptation.

I first came across this idea a couple of years back looking an interesting post on front-end style by CSS Wizardry. I use a very slightly different format which avoids using dollar symbols, mostly because I find this aids in separating SASS variables from section titles. Otherwise I pretty much use the idea as mentioned in that blog post.

Follow Up

Trying to make sure I stick to this I created a ‘CSS Contents’ Perl script. This scans a stylesheet for section titles and places a table of contents right at the start (or updates one that’s already in place). Source code available on GitHub.

Dev
Back to posts