How to Write CSS That Doesn’t Suck

A few days back, I read an article that ended up significantly improving the way I wrote CSS. Given how quickly and easily stylesheets can get horribly disorganized and out of hand, I found the tips to be immensely useful.

The article is primarily for teams of coders, who need to keep a ton of CSS organized such that many different people can understand it. Even so, I found a lot of it useful as an independent developer. Here are the things I found most useful:

  • Group related styles together. If you do absolutely nothing else this article mentions, do this. It is so helpful to scroll through a stylesheet and know that since you’ve run across your <p> tag styles, your <h1> styles have got to be around here somewhere.
  • After you’ve grouped related styles, try to arrange them by which page or set of pages they apply to. After that, create some suitably humungous, obnoxious, and obvious comment headers and make section headings, like this:
    /********************\
    ** ABOUT PAGE STYLES**
    \********************/
    This makes it infinitely easier to know which page you’re styling and also helps save your ass if you accidentally name a class or id something stupid and uninformative.
  • Make constructive use of white space. For closely-related styles, put only one blank line between styles; for more loosely-related styles, use 2 or 3. Put 4 blank lines before a new heading. This groups stuff up visually and makes it even easier to find what you’re looking for.
  • In terms of individual styles, use this standard format. It’s easy to read, it’s the near-universal standard, and more. Single-line CSS is almost never a good idea.
    .foo {
      display: block;
      background-color: green;
      color: red;
    }
  •  Indent full rule sets if they’re nested. For example, if you’re mobile enabling, indent all the styles inside the brackets after the @media tag.
  • If a style relies on another style elsewhere, or if the meaning of the styles is otherwise at all ambiguous, add a comment! CSS never has enough comments. I know it’s annoying that there’s no single-line comment, but seriously, you can afford to type that extra asterisk and slash to make your code readable.
  • Last tip: be very, very literal about your selectors, because the computer certainly will be. Do not say “header ul” when you mean “.nav”; even if you don’t have another ul in your header, this kind of selector generality is a very bad habit that can and will come back to bite you. Whenever you’re writing a selector, ask yourself: “do I want ALL x, or just some x?” If you want just some x, write a more specific selector. Even if you don’t think you’ll ever use the other types of x.

If you want more CSS tips, go on and read the full article! It’s a fun and helpful read, full of great info. Otherwise, that’s all for today: happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *