I am available for freelance work - HIRE ME

Real World CSS Practices

posted by Matt Ward on Aug 19, 2011.

I’ve been working with CSS for quite a few years now. Based on that experience, this article will share some of the best habits and practices that I have found to be helpful and beneficial in the areas of organization, performance, readability and typography.

By now, I think it’s safe to say that most designers on the web are using CSS in some capacity. Even those (misguided) individuals who are still using table-based layouts have a tendency to use CSS for some basic styling, such as establishing fonts and link colours. With that in mind, I thought it might be worthwhile cover some of what I have found to be best practices.

Before getting started, it’s important to note that these are practices and habits that I have developed based on my own experience, which includes developing different sites, my own experiments and reading from a variety of sources. While I have my own reasons for the way I do things, I am in no way presenting the following as CSS gospel that absolutely needs to be followed.

As with anything, take what you read, weigh it against your own knowledge, values and experience in order to formulate your own methodology.

Start With A Reset

When starting the CSS development of any new site, I always recommend using some type of reset. In spite of how things may appear, I find it helpful to assume that an “unstyled” page is not actually unstyled when viewing it in a browser. Instead, it is simply rendered with the browser’s default styles. Some of these will be based on the CSS and HTML specifications—such as whether an element is rendered as an inline, block or other type of element. Others are based on some common conventions that have emerged, such as the blue default link colour.

However, default styles are not identical between all browsers, and using a good CSS reset helps bring everything back to a common starting point. From there, you can begin adding the various rules that you need for your specific site, without having to worry as much about minor variations.

Of course, there are some excellent designers and developers who have expressed that they don’t like using hard resets, for a variety of reasons. Even if you chose not to use a full reset, there are benefits to using some sort similar technique, even if it’s just a matter of declaring global properties like typographical styles, document padding or default colours for text and links. Instead of having to declare these properties over and over again, simply set them at the highest possible level—often the body tag—and let it filter down through the rest of the document.

Use Inheritance and the Cascade

Which brings use to the next topic—inheritance and the dreaded cascade. These are powerful tools for writing lean, effective CSS, and I highly recommend adding them to your repertoire, and using them wherever possible.

First, inheritance is exactly what it sounds like. Elements inherit certain properties from their parent elements. For instance, suppose I write a very simple rule like this:

div p{ 
   color: #0000FF;
}

This would style any HTML paragraph element that was the descendent of a div element as blue. It doesn’t matter if that element is a first-generation child of the div. So long as it is wrapped in a div at some level, the rule will apply through inheritance. So, suppose we had something like this in our HTML:

<div>
   <p>First level paragraph text</p>
   <ul>
      <li>
         <p>List level paragraph text</p>
      </li> 
   </ul>
</div>

Both paragraphs would be styled the same colour. The element within the list would simply inherit that colour based on the single rule that we wrote.

Obviously, this is a simplistic approach, but it’s powerful in that it allows properties to be declared at a broad level and then filter all the way down through the document, without having to redeclare them multiple times.

Of course, we don’t always want to have every element in a document styled exactly the same way, and this is where the cascade comes into play. Explaining the entire concept of the cascade and CSS specificity is beyond the scope of this article (check out the W3C on this topic), but if you understand how it works, you can harness the many advantages it offers, and learn to write elegant rules for anything from the very broad to the highly specific.

The key, however, is to not get unnecessarily specific. Writing something like

html body header nav ul#mainNav li a{  
   color: #FF0000;
}

is probably taking things a little far. If all you want to do is change the colour of the links in your primary navigation to red, then something as simple as

#mainNav a{ 
   color: #FF0000;
}

will likely have all the specificity that you need. Everything else is (in the vast majority of cases) simply unnecessary. Obviously, there can be situations where you do need to get more specific for one reason or another, but generally speaking, it’s simpler and more efficient to tap into your understanding of the cascade and use the fewest possible elements in your selectors.

More On Typography

CSS is, hands down, the absolute best way to deal with typography on your website. Yes, there are some JavaScript solutions like Lettering.js that allow you to do some pretty awesome stuff, but stylesheets still remain the typographical backbone of any CSS-based site. As such, I have developed a few practices that I find to be very helpful when managing the typography on my sites.

First, I always like to set some basic rules for visual hierarchy on a page. As I’ve written before, I do like using CSS frameworks, and I’m quite fond of the way the Less Framework approaches document hierarchy. Here is a segment of the framework’s default CSS:

/*
Typography presets
------------------ */

.gigantic { 
   font-size: 110px;
   line-height: 120px;
   letter-spacing: -2px;
} 

.huge, h1 {
   font-size: 68px;
   line-height: 72px;
   letter-spacing: -1px;
}

.large, h2 { 
   font-size: 42px;
   line-height: 48px;
} 

.bigger, h3 { 
   font-size: 26px;
   line-height: 36px;
} 

.big, h4 { 
   font-size: 22px;
   line-height: 30px;
} 

body { 
   font: 16px/24px Georgia, serif;
} 

.small, small { 
   font-size: 13px; line-height: 18px;
}

Granted, this is a really simple set of rules, but it’s amazing how effective a collection like this can be for establishing the typographical hierarchy of a site. Of course, I generally tweak and add to these rules, often changing the typefaces that are used, setting colours or tweaking font sizes.

Also, I want to stress that I am not suggesting that you need to use this exact method of defining your typography. I am merely citing it as an excellent example (that I happen to be partial to) of how this useful practice can be executed. You may also want to check out the article “More Meaningful Typography,” which offers additional perspective on the issue of typographical hierarchy.

The other typography-specific practice that I like to use is to include all my @font-face declarations right at the top of my stylesheet, before any of my other typographical presets. Not only does this force a logical progression (I am not calling a typeface by name before it has been declared), it also helps with organization. Because I always know exactly where all my @font-face code is, it’s easy to make changes, such as swapping one typeface out for another—something that I do quite frequently in the early stages of a new design.

Comments & Logical Sections

With stylesheets of any significant size, it’s always a good idea to be organized. Well-commented code that is broken into logical, semantic sections is, in my opinion, the best way to accomplish this.

Any well-coded HTML document will have a clear, semantic structure. Even if you have different layouts for different pages, chances are they will at least share some key semantics and common structural elements, such as headers, navigation and/or footers.

This provides a perfect blueprint for organizing your stylesheet. Look at each of the large areas within your HTML structure and use comments (demarked in CSS with the syntax /* comment */) to break your CSS down accordingly. If you have thousands of lines of code, you may also want break these main sections down into smaller, sub-sections for increased organization.

The better organized and commented your code is, the easier it will be for you (or someone else) to read and maintain it.

A Declaration Per Line

This may be the most personal (and perhaps argued) of the practices that I will be covering in this article, but when I write my CSS I almost excusively work on a one-declaration-per-line basis. So, if I was to define a number of properties for my paragraphs, I might write something like this:

p{ 
   font-family: Georgia, serif;
   font-size: 16px; 
   line-spacing: 22px; 
   color: #444;
   margin: 1em 0;
}

For me, this is really the only way to do it. I know some people who prefer to write all their declarations on the same line. Reading their code drives me nuts. I find it much easier to isolate a particular declaration when they are all on their own lines. I don’t know about you, but I don’t always get all of my CSS declarations right the first time, and may need to change something. Even if I’m happy with the way things are displaying, something I do later on may effect inheritance or the cascade, forcing me to tweak rules I have already written. Placing each declaration on its own line makes subsequent changes much, much easier for me.

There are, however, a few exceptions to this habit of mine. If I am only including a single declaration in a rule, I will sometimes write the entire rule on a single line. This is especially true when I am working with image sprites, and require a block rules that change the background position for a number of different elements (usually icons or buttons). So I may do something like this:

div.icon{ 
   background-image: url(icons.png);
   background-repeat: none;
   width: 20px;
   height: 20px;
}
div.contactIcon{background-position: 0px 0px}
div.aboutIcon{background-position: -20px 0px}
div.servicesIcon{background-position: 0px -20px}
div.homeIcon{background-position: -20px -20px}

Because I am only using a single declaration for each of the icon classes, I can save a bit of visual space by just using a single line, without sacraficing readability. In fact, this helps to bring all the position information into closer proximity and can make the code even more readable.

There are a few other special cases like this, but for the most part, I really do perfer to keep each declaration on its own line. As already mentioned though, this is just a personal preference that I feel improves my code.

Multiple Selectors, One Rule

Efficiency of code is always something worth striving for. This can help simplify maintenance and reduce overall file size. One way of doing this with your CSS is by using multiple selectors with the same rule.

For instance, I frequently want to set all my document headings in a typeface other than the one that I am using for my body copy. For the sake of example, let’s suppose that I decided to use Georgia. I could do this by writing a separate rule for each heading level:

h1{ 
   font-family: Georgia, serif;
}
h2{
   font-family: Georgia, serif;
} 
h3{ 
   font-family: Georgia, serif; 
}
h4{
   font-family: Georgia, serif; 
} 
h5{ 
   font-family: Georgia, serif; 
} 
h6{ 
   font-family: Georgia, serif; 
}

This is entirely valid and would accomplish the desired goal. It’s also somewhat redundant. A more efficient solution would be to use multiple selectors on the same rule:

h1,h2,h3,h4,h5,h6{ 
   font-family: Georgia, serif;
}

This accomplishes exactly the same thing as using six separate rules, but in a much more efficient manner.

If I find myself writing the same property/value pairs over and over again, I always try to ask myself if there is any way to combine them all into a single rule. It’s not always possible (or even desirable), but I do frequently find logical ways of using multiple selectors to combine identical declarations.

The key here is logic. I value organization over saving a few property declarations, and if I have to sacrifice some significant level of organization (such as combining two selectors from different semantic areas), I prefer to maintain that organization and keep them separate.

When to Use Shorthand

CSS has a number of properties for which you can use a shorthand notation, allowing you to set multiple style properties with a single declaration, rather than having to declare them all individually. As you can well imagine, it’s an incredibly useful technique that can save a ton of time, but sometimes it’s not always the appropriate solution.

First, let’s start by looking at an example of one of the more common shorthand notations. Instead of writing this:

p{ 
   margin-top: 5px;
   margin-right: 10px;
   margin-bottom: 15px; 
   margin-left: 20px; 
}

We can simply write:

p{ 
   margin: 5px 10px 15px 20px;
}

The choice of margin sizes here is mostly to illustrate the shorthand pattern, relative to the individual declarations, but you can see how using a single shorthand format is much more efficient. A similar shorthand exists for padding and there are also shorthands for backgrounds, borders, fonts and a number of other properties.

So when do we use them? I generally rely on common sense. If I only need to declare one or two margins in a specific rule, than I will declare each property separately. The non-declared margins will simply inherit their values according to the rules of the Cascade. On the other hand, if I need to declare all, or even three of the margins, I will generally go with the shorthand.

Pretty straight forward.

Again, there are some key exceptions to this practice. If we look back to the example I gave regarding icon sprites, I defined each property individually, instead of using the shorthand method. I did this because I would subsequently be re-defining the background position for each class. I have typically found that when I need to do this kind of thing, it’s a better practice to define each property on its own rather than using the shorthand.

Single vs. Multiple Files

There is some debate about whether or not we should be using single or multiple files with our CSS. I don’t necessarily think that there is any clear cut answer to this question, but personally prefer to minimize the number of files that need to be downloaded for any given page. Given this, I tend lean to towards putting most (if not all) of my CSS into a single file.

There are, however, some notable exceptions. For instance, when I first set up my site, I elected to establish this blog as a subdomain, leaving the main Echo Enduring domain as my personal portfolio. When I came around to undertaking my first redesign, I wanted to streamline the process a bit, and developed a single stylesheet that set some of the key styles that would be shared between both sites. I then used secondary styles for rules that were unique to either the portfolio or the blog.

Similarly, if you are working on a large network of sites, like the Tuts+ network or the Fuel Brand sites, it can be helpful to have a single stylesheet that helps establish the universal rules that are shared among all the network’s sites. You can then use secondary stylesheets for things like colours, logos and other site-specific declarations. This can help simplify maintenance across all sites. It can also simplify the process of deploying a new network site at a later date.

The other main reason that I would use multiple stylesheets would be when adding support for various versions of Internet Explorer to a site’s design. Using conditional comments to link to separate IE-specific stylesheets allows us to write rules that will override those declared in the main stylesheet. Obviously, this is far from ideal, but it has proved to be one of the most effective and widely used solutions for dealing with the idiosyncratic (hair-pulling) tendencies of IE.

These certainly aren’t the only reasons for using multiple files; they are simply illustrative of the most common scenarios in which I find myself doing so. There are certainly other appropriate circumstances.

The one thing that I advise against, however, is using multiple files simply as a means of organizing your CSS. This simply adds extra requests to accomplish something that can just as easily be done with a good commenting system in a single stylesheet (as discussed above).

Conclusion

Well, there you have it. That actually ended up being a lot more than I thought it would when I set out to write this post. Hopefully, you either found some new and useful ideas, or you were reminded of practices that you believe in, but may not have fully following or implementing in your own work. Even in just writing out my thoughts in these areas, I’ve found that I can certainly improve my code in a number of these areas!

Lastly, I want to stress that I don’t use any sort of CSS processing tools, such as SASS or Compass. As such, I’ve approached all of these practices from the perspective of writing flat stylesheets. I can, however, see how some of the organizational techniques may not fully relevant when using some of these other tools.

Post A Comment

Also from Echo Enduring Media:

An Unfolding Tale

About the Author

Matt Ward is a digital artist who lances freely under the moniker of Echo Enduring Media, and specializes in graphics design, illustration and writing. He is also the Creative Director for Highland Marketing, a creative direct marketing company based out of Waterloo, Ontario. You can follow Matt on Twitter

Like this post? Help Promote it!

Comments

Aug 19, 2011

Jack says:

A really nice round up there Matt. Most of which (thankfully) I’m aware of, but some that I probably should start putting into practise. Have you experimented much with grid/reset frameworks? If so, which is your favourite?

Another tip I’d probably share with beginners is the usefulness of multiple classes. You’ll often see people creating masses of different classes to suit the specificness of their required styling – not realising that something like this… class=”small bold”… may solve their problems. Declaring multiple classes/ids and work wonders!

Aug 19, 2011

Matt Ward says:

Great point about multiple classes. I kind of touched on it really briefly, without any exposition, in the example of the icon sprites, since I used multiple classes there. I just didn’t really talk about it specifically.

As for CSS grids, I’ve traditionally used gs960. More recently, I’ve done a lot of work with the Less Framework. I’m also looking at the Golden Grid System as a possible framework to explore.

Aug 19, 2011

Colin says:

Awesome post Matt! A great resource for beginners and a good reminder for the experienced.

Aug 19, 2011

Matt Ward says:

Thanks dude. Even writing it was a good reminder for me!

Aug 19, 2011

Yvonne Tang says:

Interesting article. I’m actually one of those people who prefer to write all declarations on one line. It saves me a lot of time scrolling around when tweaking things (for large enough files). Not saying that my method is better of course, just that it’s interesting how everyone works differently.

Aug 20, 2011

Akhilvishnu says:

all we do daily. but you really arranged. nice round up

Aug 20, 2011

marvin says:

Ok. A good beginners guide and its really intresting for small site programmers. In websites of 10.000 lines of css codes these points are in the background ans simple basic. These big projects have nother realy big problem. Css structuring but not overwriting your own css code and performance.

Aug 20, 2011

Carlin Scuderi says:

As usual, this is a useful post. As a recent grad, I’m trying to pick up on efficient ways the industry performs certain tasks; this is exactly the kind of information I can utilize. Thanks!

Aug 20, 2011

Carlin Scuderi says:

I hear you loud and clear about the scrolling around thing. Seems like I’m scrolling forever to find things in long style sheets.

There are two things I’ve found useful for moving around quicker. One is long comments that denote headers and sub-headers for different sections, like /* ———- NAV */.
They stand out and can help you locate blocks of code quicker.

The other thing depends more on your IDE; in Coda, I have a plug-in that minimizes and maximizes blocks of CSS. So, when I’m done with a particular section, I minimize it until I need it later, when it can be easily reversed.

Aug 20, 2011

Agustin Giannastasio says:

Hey, good post!
You also could shorthand this two lines:

font-family: Georgia, serif;
font-size: 16px;

with:

font: 16px Georgia, serif;

Cheers!

Aug 21, 2011

Matt Ward says:

yep! Thanks for pointing that out. I think it’s a lesser known type of shorthand!

Aug 21, 2011

Krzysztof Kotlarski says:

I’ve been wondering. What’s the point of using div.icon when you can just write .icon?

Aug 21, 2011

Matt Ward says:

Good point. There may be some circumstances, but for the most part it’s true that the div is unnecessary. Thanks for pointing it out!

Aug 21, 2011

Josh says:

font{} is a very dangerous css shorthand to use.You want to be careful with that. Using a css rule of font {} resets all the other styles that you don’t implicitly declare, so font-weight, style, etc go back to normal.

That being said, I use it all the time. :)

Aug 22, 2011

Nicolas G says:

Hello and thank you for this article it is very true… Just something to say about inheritance i recommand to use it on small pages. Because webperf matter it is not recommanded if you have lots of tags and files, the dom has to work a lot.

More generally Reusability is a subject that should be talked at the begenning of the project to Keep It Stupid Simple.

Aug 23, 2011

Rafael Trabasso says:

I prefer other methods for dealing with CSS. I separate all my CSS files and link them on a main style.css file. Only when I’m done with designing the site I join them in one stylesheet.
AND I write all the CSS declarations on one line. Helps me find stuff faster.
Well stuff work differently with different people after all :)

Aug 23, 2011

Dominic Pettifer says:

“The one thing that I advise against…is using multiple files simply as a means of organizing your CSS. This simply adds extra requests to accomplish something that can just as easily be done with a good commenting system in a single stylesheet.”

The exception to this is if you’re using some sort of server-side auto minification and combining code where multiple CSS files are combined into a single file and minified at runtime (and then cached of course). Or maybe you have this done in a deployment script.

Then multiple CSS files for organisation becomes a perfectly sensible proposition.

Aug 23, 2011

Rick Huby says:

I personally go for many small CSS files for development but then use a minification tool to merge and compress them into one file (e.g. minify, combres or JAWR).

I find it is much easier to separate out the CSS logically this way, often I have something like: reset.css, main.css, nav.css, footer.css, articles.css and maybe a few others.

PS. It’s nice to see someone else who writes one line CSS instructions like me :)

Aug 23, 2011

Vincent says:

I do the same and it allow me to never make inline css with more than 7k css line in my website.

For those who want to learn how minifty things you should check this very good how-to :
http://www.samaxes.com/2009/05/combine-and-minimize-javascript-and-css-files-for-faster-loading/

One tip : do the minifiying only in [pre-]production. Because having to rebuilt files is quiet long for the small daily modifications.

Aug 23, 2011

Chris Raymond says:

Regarding use of a reset stylesheet: I urge everyone reading this to PLEASE STOP USING LINE-HEIGHT:1 as your default reset. It’s bad typography and it makes text far less readable (and you do want people to read your content, right?)

Short of very large headlines, like 36px or larger, it is a very bad idea to have a line-height (or “leading”) the same size as text. It makes body copy very hard to read because the eye does not have enough “white space” to follow to the next line. It is poor typography.

Yet, nearly all the most popular reset.css stylesheets define line-height to 1. The default should be at least 1.25.

Aug 23, 2011

Matt Ward says:

Excellent point. I generally set mine to about 1.3 – 1.4, but not in the reset proper. It might certainly be worth moving this to the reset. Thanks!

Aug 23, 2011

Jess T-R says:

Great post! I’m a total newbie to CSS but looking forward to learning more, and I will definitely start using these tips. Just created my first attempt at a website and I definitely could have used better organization to make my life easier.

Aug 23, 2011

Daquan Wright says:

Hey Matt, do you think it’s a good idea to double space css lines? I write my css like yours, but double space it. I’m not sure if I’m just wasting space, perhaps I don’t need that much readability? Don’t want to go overboard, hehe.

@Yvonne: It’s cool, we all have our ways of solving problems. That’s what makes the web such an awesome domain to work in.

Aug 28, 2011

TJ says:

Great post! Another useful source for css best practice is http://csslint.net/about.html#docs. Although some what strict, passing the test with little or no warnings is an indication for good css. It’s also important to know that css selectors are read from right left as described on http://css-tricks.com/6386-efficiently-rendering-css/.
It doesn’t really matter if you write your css on one line or multiple lines (I prefer multiple). In either case you should use a compressor for production use: http://www.minifycss.com/css-compressor/ or http://developer.yahoo.com/yui/compressor/.

Oct 3, 2011

Deepen Dhulla says:

very informative for web developers.

Nov 22, 2011

Jimmy Vonner says:

Thank you, very helpful. Sometimes is a nightmare to validate css

Mar 12, 2012

santa says:

great blog

Jul 1, 2012

The man with the white space says:

“I know some people who prefer to write all their declarations on the same line. Reading their code drives me nuts.”

div.contactIcon{background-position: 0px 0px}
div.aboutIcon{background-position: -20px 0px}
div.servicesIcon{background-position: 0px -20px}
div.homeIcon{background-position: -20px -20px}

And reading the code of people who don’t know how to use columns drives *me* mad! ;-P

div.contactIcon {background-position: 0px 0px}
div.aboutIcon {background-position: -20px 0px}
div.servicesIcon {background-position: 0px -20px}
div.homeIcon {background-position: -20px -20px}

Jul 1, 2012

The man with the underscores instead of white space says:

Unfotunately the spacing gets htmled out so let’s see whether this conveys the idea of columnation…

div.contactIcon _{background-position:__ 0px _ 0px}
div.aboutIcon ___{background-position: -20px _ 0px}
div.servicesIcon {background-position:__ 0px -20px}
div.homeIcon ____{background-position: -20px -20px}

Leave a Comment

Links

Top Commenters

Thanks so much to these awesome people for joining in on the discussion!

Copyright © Echo Enduring Media 2009-2014