Follow me on Twitter!

Dont Trust This Guy why not take my word for it? A blog by Jim Jeffers

The Art and Zen of Writing CSS

I’ve been writing pure html/css layouts for well over eight years now. While I’ve found best practices in the form of convention and documentation to be useful. They don’t prevent some of my CSS nightmares from reoccurring. They merely make them less painful. My solution is to follow guiding principles in the way I write stylesheets. These principles form a foundation for writing stylesheets that will be easier to work in as the project grows.

Lesson One: Only be Specific When You Need to Be.

There is a hesitation to fully utilize the cascade. Many people who have worked in CSS for a long time tend to utilize very powerful pseudo-selectors to target specific elements. This is all well and good but it also creates a dangerous habit. We become uncomfortable writing rules that are not highly specific.

This has been a hard lesson learned many times over. My preference has always been to be accurate. I’d write CSS rules that were really detailed and specific. But this is bad. Specific rules paint you into a corner and make reuse very difficult. Instead, use the most general rule you can to get the job done and only write rules that are more specific when the situation presents itself. See the example below:

Now it’s true that the second rule would apply to every paragraph tag on the site. But at first this is fine. Imagine how simple it is to add more specific rules later. As projects grow and styles become inherently more complex by necessity, the situations where we need to become more specific will naturally present themselves. If we are generic from the start we can take advantage of the cascade and overwrite rules with more specific rules when we need to.

To see how bad it can get take a look at these two examples (the third set of rules is an example of adding additional style info with a more specific selector):

This seems like a fundamental lesson in CSS. We can write styles that apply to many objects and the more specific rules will take precedence. Most people who write CSS know this. What’s not usually brought up is the fact that it’s much safer to avoid the complexity created by writing more specific CSS. There are two laws I would propose in regards to specificity in CSS:

  • The complexity of your stylesheet is directly correlated to how specific your selectors are.
  • Refactoring CSS selectors to be less specific is exponentially more difficult than simply adding specific rules as situations arise.

Lesson Two: You Must Start Somewhere.

Whether you work alone or on a team you need to have a starting point in your stylesheet. A starting point is a generic set of rules that defines how we expect our environment to behave. This is generally important when working in CSS but infinitely more important when working on a CSS document with multiple contributors. Everyone needs to be on the same page and having a baseline foundation for our stylesheet is the best trick we have in our arsenal for achieving exactly this.

My starting point is Eric Meyer’s Reset CSS. Unfortunately for your own productivity, it seems that using a reset stylesheet is a controversial subject. Some experienced with CSS consider these tools to be unnecessary or just plain bad. But the truth is that we all use them in one form or another. The real problem with reset stylesheets is that they were named “reset”. They are not resets but rather they serve as our baselines, our foundations, our intentions for how we want our environment to behave.

The reality is if we don’t use CSS resets we implement them in a much more difficult manner. We repeat ourselves where we have to throughout the document in order to achieve a standard desired behavior. The best example are margins. Every web browser platform has it’s own default styles for margins on different elements. There is no way in hell any of us can memorize the variations of these defaults in our minds let alone compensate for them without taking a serious productivity hit.

If you don’t define your starting point then you inherent every browser’s own pre-defined starting point. This leads to a much more hostile environment for our work to be deployed. We’re giving up control of our environment. It’s much less predictable. It’s actually very very scary.

That’s not to say reset CSS files are the holy grail to writing good CSS. Far from it. They can be a pain if you don’t tailor them. For example, many people don’t like certain settings used in some reset CSS files. A common example is that the ’strong’ element is no longer bold. But that’s because the reset is distributed as a pure example. It’s up to you and your team to change this reset file for your own purposes. If you want strong to be bold adjust the reset. Ultimately, you will develop your own reset.css (though really I think we should call it base.css) over time. The key lessons here are:

  • Base stylesheets grant CSS authors control over their environment.
  • Base styles are key to creating a shared set of assumptions or expectations amongst multiple contributors.
  • Base styles do not guarantee cross browser compatibility but rather buy us and our team members predictable outcomes.

Lesson Three: Rely on Specificity Over Order.

A basic principle in CSS is that if you write two equally specific rules the latter takes precedence. In other words, order matters in your CSS. But this is dangerous. Order only matters if you let it matter – by writing rules with selectors of equal specificity.

As stylesheets grow in size they become more cumbersome to manage. To remain productive in our files we break them down into sections. Or we separate our rules into entirely separate files.

A reliance on the order our code makes it very brittle or fragile. When we need to incorporate a strategy for organizing our code we can easily disrupt the original order the rules appeared in. This is significant because as I stated earlier it’s more manageable to write selectors that are less specific and more general. That does not mean you should incorporate the principle of order as a technique for maintaining a stylesheet with generic rules. If you have two rules of equal specificity that conflict with each other then you need to make one of them more specific in the interest of writing a stylesheet that is flexible enough to be reorganized in a structural framework.

Additionally, most of the occurrences in our stylesheets that provide situations where we have rules which overrule each other due to their order of appearance tend to deal with duplicate selectors. These cases are ideal scenarios where our CSS could potentially be refactored.

The key take aways from this point are:

  • Stylesheets that have a strong reliance on order of appearance are inherently more brittle and more susceptible to problems when we attempt to restructure or reorganize our documents.
  • Rules that are overwritten due to their order of appearance typically could or should be refactored.

Lesson Four: Be Clear and Expressive.

You need to be clear on what you expect. You need to be clear on how things should be done and handled in your document. How do you do that in CSS? Simply with commenting. We can provide ample amounts of documentation in our CSS files simply by commenting. We can use comments to:

  • Define best practices.
  • Denote organizational sections.
  • Provide references for resources.

There are two problems here. The first is that not enough people utilize comments in their stylesheets. The second is that many authors don’t see the need to. Yes the latter is probably the reason for the former.

Let’s look into why we might not think commenting or documenting our expectations and best practices in the document may be worthwhile. The first reason is that comments make our CSS file larger in file size. Yes – this is certainly true but we can easily use YUI compressor or write simple scripts to automate the process of minifying and removing comments from our production code.

The second reason might be that you’re the only author touching the stylesheet. This is incredibly short sighted. Always always (always!) plan on someone else touching your stylesheet at some point in time. Chances are you are not the only one who will be working on the project for eternity. In other words – count on the fact that someone else will eventually be writing code in your stylesheet as well. You may as well make it clear to them as to how they should do it to maintain a consistent stylesheet. Otherwise you may find yourself cleaning up a big mess later when you’re called back to work on a broken site!

Being expressive is easier said than done though. How do you go about declaring how you expect things to be done? I personally embed my best practices in a short set of directions complete with an example in a comment at the top of all of my stylesheet files. The snippet looks like this:

The point here is you can utilize comments to make things very clear in a simple elegant fashion. Just document your CSS as you should be documenting all of your code. Textmate users can benefit from a CSS commenting bundle I put together a few years ago to quickly document and section apart their stylesheets. What you need to remember regarding expressiveness in your CSS is the following:

  • Utilize comments to define how CSS should be formatted and written for other authors.
  • Always count on the fact that someone other than you will probably work in this document at some point in time.
  • Utilize comments to organize your code into sections. Comments can effectively become a navigation system within your CSS document.

43 Responses to This Article.

  1. Niels Matthijs Says:

    Awesome (awesome!) post. Even though these rules appear simple and basic, my experience is that they are hardly applied and/or even understood.I’ve been hammering on clean css for the last year or so, though I tend to focus more on writing about flexible css (which is nearly the same). Still, it’s difficult to get the message across to people. Just check all the blogs. Flexibility and readability aren’t the most popular topics. People rather read about bugfixes and techniques, while the biggest problem of css today is situated elsewhere.Keep on blogging about this. The more people will follow, the better webpages will become.

  2. Tim Says:

    Thanks for those great tips. I recently worked on a project were I came in on it the week before launch to help clean up the code. Would have made my job 10x easier if they even followed half of your points. One question though when you say “refactored” what do you mean by that?

  3. Nicolas Gallagher Says:

    Indent proprietary properties with two spaces. Keep these properties directly below the proposed property.Some good points. A couple of comments if that’s ok.Lesson One starts with “There is a hesitation to fully utilize the cascade”.Lesson Three states “Order only matters if you let it matter…A reliance on the order our code makes it very brittle or fragile.”To me, these two statements contradict each other. Order is also a fundamental part of CSS…so it is supposed to matter.Lesson Four contains a code block comment: “Indent proprietary properties with two spaces. Keep these properties directly below the proposed property.” I’d suggest that if you’re using vendor-specific prefixes then these properties should appear above the “proposed property” so that they will be overridden when fully implemented in line with the specs.

  4. Zachary McInchak Says:

    been writing pure html/css layouts for well over eight years now. While I’ve found best practices in the form of convention and documentation to be useful. They don’t prevent some of my CSS nightmares from reoccurring. They merely make them less painful. My solution is to follow guiding principles in the way I write stylesheets. These principles form a foundation for writing stylesheets that will be easier to work in as the project grows.

    Lesson One: Only be Specific When You Need to Be.Good points here. I’ve been pairing down my style sheets wherever possible so I can more easily adapt the code to a new design. Doing this also makes it so much easier to go through and make edits. I think that I might be using only a partial reset, but I’ve seen the full versions and they seem a bit excessive.

  5. Nicolas Gallagher Says:

    The JS you’ve got running the preview box seems to have prepended the content of my clipboard to my previous comment! You should remove the first 2 sentences of my previous comment. Thanks

  6. L’art et la manière d’écrire du CSS | KubX Says:

    [...] The Art and Zen of Writing CSS. Tags:css [...]

  7. Amber Weinberg Says:

    Great tips, I also struggle with being too specific, especially when the client has given me all the mockups and I find out later that that blue button was used multiple times, so I either have to go back and change the CSS to match more globally, or be a bit unsemantic ( which I hate)

  8. Andrew Says:

    Nice tips. I especially like your snippet of best practices. I might have to steal that idea.

  9. Phil Thompson Says:

    A very interesting write-up on CSS and one that every new front-end developer (and some experienced ones too) would do well to read.I’ve always tried to lay out my stylesheets in the following order:1. reset (baseline) styles2. common tag styles e.g padding/font-sizes on p’s, h1-h6’s, ul/ol/dl’s3. common classes4. more specific styles5. style for very specific cases (e.g. different styled pages)As I find it limits issues later on in the website’s life.The more I read other developer’s CSS, the more I despair; it does seem that for some people the only goal is to make the code as concise as possible – scrunching it all into one line and be damned the next developer when they come along to maintain it.

  10. Jena Says:

    As someone who has been learning CSS on her own, I found this post very helpful. Thanks!

  11. Jbcarey Says:

    Great set of rules. Good advice.

  12. Matt Says:

    Excellent article Jim. I’m guilty of not following a few of these rules and I’ve paid for it. I agree with your interpretation of the css rest also. Definitely better to look at it as a base. I guess it also comes down to personal preference and trust in the browser industry (which should go up once IE6 finally dies).

  13. David Siegfried Says:

    These are all great tips. I use many of these myself especially the Eric Meyer CSS reset. I have also taken to including a header section comment that explains the sites main colors, authors and some CSS writing tips for future authors.

  14. Yaili Says:

    Refactoring CSS selectors to be less specific is exponentially more difficult than simply adding specific rules as situations arise.

    I couldn’t agree more with this guideline; it can make you avoid many a headache.Actually the entire post brings up very important points and very sensible tips.Something I’d like to add about commenting: even if *no-one* ever touches that CSS file again, you probably will, and you probably will not remember why you’ve made some stuff in there, how you solved something or look at something and think “boy, wasn’t I silly 2 years ago, why did I put this here, let’s remove it NOW” — and it breaks everything. So commenting is not just for others, but for yourself.As a side note, I’d go a little bit crazy if I had to follow the rules on your directions example, but that’s just me :)

  15. Adam F Says:

    Great post, I try to incorporate these best practices into all my style sheets, alas sometimes bad habits creep back in and my world becomes a little too specific. If I were to add one thing it would be a lesson before one, the importance of planning. Too often have I fallen into the trap of finishing a design and diving head first into the mark-up and styling, only to quickly see things turn to a mess. Both Andy Budd (CSS Mastery) and Andy Clark (Transcending CSS) identify the importance of planning your layout first, “measure twice, cut once.” The best way of achieving this will be different for each individual, but often the simplest way is the best, taking a print out of your design and making notes of what goes where and how to mark up your page can really help you see your design as a big picture and avoid getting specific when it’s too late.Taking this approach also helps to avoid turning your design into a div mess, with div’s inside of div’s inside of div’s. Obviously this could be a blog post on its own (the importance of minimising your div’s) but spending that bit of time before you start up your text editor makes a big difference when trying to produce clean mark-up and styling.

  16. Jim Jeffers Says:

    @Nicolas Gallagher:

    To me, these two statements contradict each other. Order is also a fundamental part of CSS…so it is supposed to matter.

    Yes you are absolutely right! However, it only matters as this is a logical way to deal with conflicting selectors of equal importance. My argument is that it is consequential and cumbersome to write rules of equal importance as then we must depend on the order of appearance in our CSS. In most cases we do not need to write two selectors of equal weight for different rules. And because of this what I am proposing here is that we shouldn’t.

  17. Jim Jeffers Says:

    @Nicolas Gallagher:

    You should remove the first 2 sentences of my previous comment. Thanks

    Sorry about that!

  18. Jim Jeffers Says:

    @Andrew:

    I might have to steal that idea.

    Please do!

  19. Jim Jeffers Says:

    @Phil Thompson:

    I despair; it does seem that for some people the only goal is to make the code as concise as possible – scrunching it all into one line and be damned the next developer when they come along to maintain it.

    Sadly that’s very true. If only those people would learn they can minify their CSS in production and still keep it readable in the development environment. The developer time (cost) wasted on poorly written code is a huge project burden.

  20. Jim Jeffers Says:

    @Yaili:

    I’d go a little bit crazy if I had to follow the rules on your directions example, but that’s just me

    It’s not THAT bad :) I have been using that set of guidelines on projects for the past two years now with much success!

  21. Jim Jeffers Says:

    @Tim:

    One question though when you say “refactored” what do you mean by that?

    That means revised, simplified, cleaned up. Let’s say you have a lot of duplicate CSS in different places. Well refactoring would be going through the CSS and cleaning all of those up. This applies to any code – for more information seek wikipedia: http://en.wikipedia.org/wiki/Code_refactoring

  22. Jim Jeffers Says:

    @Adam F

    Thanks Adam! Yes – you are absolutely right. Designers should take the time to denote a plan on how they intend to express a design in markup prior to coding the CSS let alone the HTML markup (which everyone should be doing before writing styles – if not wouldn’t you be psychic?)

  23. John C. Bland II Says:

    Dude…write a book! Ok, I already told you that on Twitter but I had to repeat it for Google. ;-) Ok, this article makes me feel normal again. I always hark to CSS developers on projects, as you may recall my “rules” from previous gigs together, to write reusable CSS. Many see it as a burden and groan but as a web developer it allows me to free-flow with the markup and apply styles as needed.Thanks for removing my fear of being crazy. :-)

  24. Jim Jeffers Says:

    @John C. Bland II:

    Thanks for removing my fear of being crazy.

    Nope – you’re definitely not crazy :)

  25. Misael Says:

    I have a bad habit of relying on order of appearance in my style sheets but am trying to break myself of it. Thanks for the helpful tips, good read.

  26. Andy Ford Says:

    Very nice food-for-thought for CSS beginners. I’ve been getting a designer colleague get up to speed on CSS, and this will come in handy.One nit to pick: Eric Meyer updated his reset CSS over two years ago now http://meyerweb.com/eric/tools/css/reset/index.html. You might find it a little more stable than the outdated reset reloaded version.

  27. Jim Jeffers Says:

    @Andy Ford

    Thanks Andy! I’ve updated the link to point to the most current reset CSS.

  28. Dan Ritz Says:

    Awesome. I’m totally stealing the “keep our CSS clean” chunk of code with some additions. I’m also still undecided about the reset (or base) and will read up on Snook and Jens articles. I’m guessing I’ll rework it into a cleaner base.css.I love the articles that are more about practical ways to think about CSS. There’s plenty of general tips and tricks. This is much more valuable and probably way more difficult to write.Thanks and high-five!

  29. Ian Parr Says:

    Nice to hear an approach which is familiar to me. Good article, I wish I’d started with this approach back in the day. These attitudes and, particularly, the Meyer reset have made the CSS work I do easier and more simple.

  30. Martin Kulakowski Says:

    Right on, Jim! All excellent tips, thanks for sharing!

  31. David Oliver Says:

    Spot on!I’m currently in the process of settling on guidelines for my usage of CSScaffold. Certain abilities it gives you can result in less than optimum CSS, but if you limit your usage of its features and only use when appropriate the approaches you outline can still be adhered to.

  32. Schuhgrößen Says:

    comments to organize your code into sectionsThank you for the four very good lessons! Often i´ve the problem with no comments in my code – the time to write is most shorter, than the search–time after

  33. Warren Says:

    @Jim Jeffers:

    most current reset CSS.

    just checking out your cool quoting mechanism

  34. Ben Atkin Says:

    The reality is if we don’t use CSS resets we implement them in a much more difficult manner.

    When I read this, I was instantly reminded of Greenspun’s Tenth Rule:

    Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

    I’m going to start insisting on using resets. There’s science to back me up!(This is not to say that other people can’t be efficient working without resets. But I know it’s more trouble than it’s worth for me.)

  35. Ulyses Says:

    I agree with (some of) what you say, I learn (some of what) you are so gentlemen to share with us.I don’t (completly) agree on the styling for CSS rules. This is probably the most important thing when writing CSS. Later on, you can be misslead by the way you write it down earlier, so I believe in a semnatic aproach rather then a alphabetized one.I even made a rule, I “named a wizard” (like in focus-acitve…) to help with that, and I believe in more then a rule per line.

  36. Pol Moneys Says:

    Thanks for sharing. nothing new but classy.

  37. Web Dev Tutorials 1# | Booto’Blog Says:

    [...] The Art and Zen of Writing CSS By Jim Jeffers, March 7th, 2010 Site: DontTrustThisGuy [...]

  38. CSS Specificity And Inheritance – Smashing Magazine Says:

    [...] [...]

  39. CSS Specificity And Inheritance | Web Design Cool Says:

    [...] good rule of thumb can be found in Jim Jeffers’ article, “The Art and Zen of Writing CSS”: Refactoring CSS selectors to be less specific is exponentially more difficult than simply [...]

  40. Nathan Says:

    that will be eaTo add to the concept “Lesson One: Only be Specific When You Need to Be.”I see a lot of people over-specifying widths when they should not. Like on your average block element – don’t specify its width if you want it to take up the entire width of its container.That way, if you ever change the parent container’s width the block elements with unspecified widths it automatically adjust properly.You’re also free to apply margins & padding to a block element that hasn’t had its width specified and you’ll get the desired result. Put 20px padding on an unspecified width block element and it’ll fill its container and have nice padding. If your width would have been specified, you would have had to subtract your padding from the container’s width to get the proper size.Long story short: don’t specify widths unless you need to. Your block elements will behave more like you would probably like them to.

  41. Nathan Says:

    @Nathandon’t know where that wierd text at the front of the post came from… user error i imagine

  42. TG Designer » CSS Specificity And Inheritance Says:

    [...] good rule of thumb can be found in Jim Jeffers’ article, “The Art and Zen of Writing CSS”: Refactoring CSS selectors to be less specific is exponentially more difficult than simply [...]

  43. Greg Says:

    Utilize comments to define how CSS should be formatted and written for other authors.
    Always count on the fact that someone other than you will probably work in this document at some point in time.
    Utilize comments to organize your code into sections. Comments can effectively become a navigation system within your CSS document

    As a fledgling web desinger this was a very good read. Thank you very much for the input on CSS standards. Yes, I know that you weren’t really commenting on standards specifically, but if these were standards life would be easier.. I am working on a project right now that is hard to know what the author was thinking and as a result have recoded huge portions of the site.Explination in the code would have been VERY helpful. Thanks.

Leave a Reply

Meta Information

This post was filed under code and tagged with: , , .

This Post as a Feed

The content of this post and it's comments can be subscribed to as an RSS feed.

DontTrustThisGuy.com and all contents copyright 2003-2009 by Jim Jeffers, unless otherwise noted.Written in valid XHTML and a participant of XFN while being powered by WordPress
Contents under Creative Commons License. Visual design, layout and Cascading Style Sheets may not be reused without permission.
Entries (RSS) and Comments (RSS)