CSS Best Practices

This is not a post about using specific CSS properties. Nor is it a post about how to integrate CSS with HTML documents. This post is just about the best ways we’ve found to write useful, concise and reusable CSS.

Selector Names

Selector names are always going to be a tricky subject. Unless we build an incredibly comprehensive CSS framework then nobody is going to be able to tell you what classnames or IDs to use for everything.

There are a few reserved classnames but mostly, when it comes to new classes or ID names, you’ll be on your own. This freedom may sound goo but there are some things you will need to think about before you start naming your selectors.

Try to be descriptive about the structure of the HTML rather than the style of the CSS. This means that when you’re looking through your CSS you can more easily understand what is being styled.

If you can avoid style-based naming then you will also avoid building in permanence. In other words, if you create a class called ‘red-box-left’ then that box will always have to be red and on the left for your classnames to retain any sense of what’s going on in your document – If, however, you called it something more structural, like ‘inset-box’, then it could be styled red or blue and floated left or right without the classname becoming confusing or loosing any sense.

Selector Cascades

If you can help it, keep your selector cascade to the bare minimum. Over qualifying an element will add extra weight to your CSS file and will also slow down rendering once the CSS is loaded.

Check through your selector cascades along side the HTML you’re writing them for, you may find that your cascades are needlessly lengthy.
You may find you have a cascade like this:

body #page .main-area .primary-content .component .component-heading h2 a {...}

Firstly, we need to understand why the cascade might be written this way – The coder may have been trying to target a particular instance of an anchor on the page; an anchor that only occurs within an H2 within a ‘.component-heading’ within a ‘.component’ within the ‘.primary-content’ block within the ‘.main-area’ within the ‘#page’ within the BODY.

We could re-write this cascade a number of ways to achieve the same targeting.

The first thing we could drop is the BODY reference – what’re the chances of an anchor appearing outside the BODY tag?

We could probably drop the ‘#page’ reference for the same reason as the BODY.

Next we have to decide what we are targeting. If we’re targeting all anchors within the ‘.main-area’ block then why not just use:

.main-area a {...}

The same goes for all anchors in the ‘.primary-content’, all anchors in a ‘.component’, all anchors within a ‘.component-heading’ or all anchors in an H2.

Given the length of this cascade we probably need to think about something more specific. Maybe we’re looking a something peculiar to an anchor within a ‘.component-heading’ when that ‘.component-heading’ is within the ‘.primary-content’ block. In which case we would still use a shorter cascade:

.primary-content .component-heading a {...}

You’ll notice that we don’t need to specify either the ‘.component’ or the H2.
You should also avoid needlessly replicating the HTML structure. You don’t need this:

ul li a {...}

The LI in this case is implied by the UL – it doesn’t need to be present in the selector cascade – so the cascade can be written as either

ul a {...}

or

li a {...}

Similarly, you don’t usually need to add the element name if you intend to identify it using a class or ID:

div.classname {...}
span#idname{...}

These are pointless (especially in the case of the ID) and will only cause your CSS to be heavy and slow.
There are times when you may need to extend your cascade but you should always bear in mind that every extension to a selector cascade makes your CSS heavier and slower.

Having said that, longer selector cascades are preferable to the ‘!important’ rule

Avoid using ‘!important’

The ‘!important’ rule is there to make sure that particular rule trumps all others. This is a very useful concept when you’re working out a quick patch for some CSS that someone else wrote 15 months ago and now no-one can remember what’s what.

This is not a very useful rule when you’re having to over-write someone else’s ‘quick patch’ that uses the ‘!important’ rule.

It’s worth finding out how to get by without using ‘!important’ because it will only cause problems later on if you do use it.

Colors

Hex color values will play an important role in any layout especially if you’re trying for an optimized style sheet.

Here are a couple of ways to make life easier for yourself when you’re working with colors.
You don’t have to specify 6 characters for three pairs. If you’re writing in a color value that consists of three pairs you can specify each of those pairs as a single hex digit. For example:

#3af

is the same as

#33aaff

The other thing you should be doing to make life easier is to remember to always use lower-case letters in your hex color definitions.

#3ea4c0

is much easier to read at a glance than

#3EA4C0

Zero

Zero will always be zero. It doesn’t matter if you’re dealing with millimeters or kilometers; 0mm = 0Km. This means that you don’t need to specify units when the value is zero:

margin: 0 2px 5em 0;

is perfectly valid – the browser doesn’t need to know what units it’s dealing with if the value is 0.

Margins and Padding

There are a few shortcuts you can take when you’re writing margin and padding declarations.

The standard way of writing a margin or padding declaration uses four values for top (t), right (r), bottom (b) and left (l) in that order. However you don’t necessarily need to specify each of those values. If particular values are the same then it’s possible to shorten the declaration. Here are the possible combinations:

10px 10px 10px 10px = [trbl] = margin: 10px;

10px 5px 10px 5px = [tb] [rl] = margin: 10px 5px;

10px 5px 20px 5px = [t] [rl] [b] = margin: 10px 5px 20px;

Coding Style

When you’re writing CSS it’s easy to loose yourself in your task and forget everything else. The easiest thing to forget is that the styles you’re writing may need to be edited or managed by someone else or may need to be revisited by yourself in say nine or ten months time – will you be able to remember every detail of your styles? will you be able to remember why things were styled in a particular way? Probably not which is why we need to stick to a standard that everyone is familiar with – this will help to make our CSS clearer to anyone who reads it.

So, here are the rules for our standard:

1. One declaration per line.

Some coders find it easier to write CSS as if they were writing in sentences with lost of declarations on a single line – this makes things difficult to untangle when you’re under pressure to get things fixed. It’s much better to have each property/value pair on a single line so that you can see exactly what’s going on without have to read entire lines to get to the bit you’re interested in.
See if you can spot the error here:

.box {width:100px;height:50px;padding:10px 20px 3px 15px;margin:20px;
border:1px solid #EF77F3;float:left;text-indent:10px;font-weight:bold;
color:#e9e9e9;clear:both;border:2px solid #c00;text-align: left;}

Did you find it? Not easy is it.

2. Spacing

Although it may seem odd to talk about introducing extra characters when you’re also thinking about optimization, you also have to consider the usability of the CSS file after you’ve created it. Indentation will make it easier to see where rules start and finish and spaces between property and value will make them easier to read.

3. Alphabetization

In the example we looked at above, the properties were all jumbled up together with no real way of untangling them. Some coders will write in a similar way but with a little grouping for, say, the block properties (width, height, padding, margins and so on) on a single line and other groups such as font-related properties or coloring on other lines – this is still difficult to read and there’s no easy way of defining what order each line should be in or how to order all the lines in any rule so that other developers can easily find the properties they might need to change.

So, what happens to our example if we apply the three coding standards above:

.box {
    border: 1px solid #EF77F3;
    border: 2px solid #c00;
    clear: both;
    color: #e9e9e9;
    float: left;
    font-weight: bold;
    height: 50px;
    margin: 20px;
    text-align: left;
    text-indent: 10px;
    padding: 10px 20px 3px 15px;
    width: 100px;
}

The error we talked about earlier suddenly becomes so much easier to spot: two border declarations with different values.

If you always write your CSS the way we described above then you should be able to limit your errors and leave your code readable for other developers – hopefully you should also be creating smaller CSS files too!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s