Writing Clean CSS3 Code [updated]

  • 1st September, 2010
  • Tom Kenny
  • Articles

One of the main problems with writing CSS3 code are the vendor prefixes. These are the -moz- or -webkit- you see before properties such as border-radius or text-shadow. They’re a necessary evil at worst and you’ll have to use them to get the most out of what CSS3 currently has to offer.

So what’s the problem? I’m very much a fan of the single line approach to writing CSS as seen below. It allows elements to sit under each other nicely, making them easier to find. Good commenting also helps.

The downside of vendor prefixes is declaring the same value more than once. Combine this with the single line approach above and you can see it starts to get messy with every CSS3 declaration on the same line. This will only get more difficult to read, with more CSS3 properties used.

I’m a designer so I can’t have my code looking messy and ugly, especially when you’re working on sites you know your workmates will be working on some point too. My solution is to keep the regular old CSS on a single line but split CSS3 onto separate lines defined by vendor prefixes. Not exactly earth-shattering but now it’s cleaner and much easier to read and edit all those declarations of the same property. They all sit under each other making them easier to compare to one another. I also start with the shortest at the top working my way to the longest, again just keeping everything consistent, neater and easier to read.

It even works well with extra CSS3 properties.

I take the same approach if I’m using rgba for the background colour of an element. The first declaration is for older browsers such as IE which ignore the rgba line.

Over to You

How do you deal with keeping your code beautiful and using multiple CSS3 vendor prefixes?

Update: As a few people have pointed out in the comments as well as a tweet from @nathansmith, you should be putting the vendor prefixes first and the final spec version last. See CSS-Tricks‘ comprehensive explanation.

by @tkenny

You should follow me on Twitter here

Subscribe to Inspect Element by email to get updates on new articles, tutorials and WordPress themes: