Do you write bad CSS?

Written by on

CSS is so powerful because you can do so much with it. It's constantly improving. CSS3 is an amazing advancement for web developers. 

However, since you can write CSS however you'd like, a lot of people aren't very good at writing it - myself included. Over the past few months, I've challenged myself and our team to improve. Here's what I've learned: 

Don't style elements by ID

It's tempting. You can do it. But, you shouldn't. Avoid it at all costs. 

IDs are meant to be unique. If you style an ID tag, it means you're styling a unique element; therefore, you're not writing reusable CSS. Remember the DRY principle? Styling an ID is a blatant violation of the DRY principle. 

Avoid more than three levels of nesting

Deep nesting lends itself to CSS that isn't reusable. If you have more than three levels of nesting, you're probably styling elements based on their container. When you have many levels of nesting, the context of an element dictates its style. Most of the time deep nesting will cause problems.  Deep nesting should be the exception, and not a common pattern.

Naming is hard

Naming is notoriously difficult, and it's just as difficult while writing stylesheets. Try to describe the element you're styling in English. Don't skimp on naming in exchange for less typing, but don't use extremely long class names either. 

Do you want to understand your code in 6 months? Try hard to improve naming. 

Think of elements in terms of modules or components

If you start thinking in terms of modules and components, you'll start to write better CSS. Sometimes, context matters; and therefore, calls for you to do some nesting. More often than not, nesting is bad. 

Components should be reusable. If you want to put a component on a different page in a different context, it should still look the same. If it doesn't look the same, it's either a slight variation of the component or its a completely new component altogether. 

Split components into separate files

Have you ever worked on a project with one massive, ugly, disorganized stylesheet? I think we all have - and it's no fun. A good practice is organizing your stylesheets by component. Styling some tabs to be used throughout your application? Use tabs.css as a filename. What about a header component? Use header.css.

If you're worried about including many stylesheets in production, don't. You should be using stylesheet compilation. If you're using Rails, we have the asset pipeline to help us do this.  If you need a standalone solution, try YUI compressor.