Menu Search
Jump to the content X

7 Principles Of Clean And Optimized CSS Code


Some of you may remember the days when 30KB was the recommended maximum size of a web page, a value which included HTML, CSS, JavaScript, Flash, and images. I find with every new project with even the slightest bit of complexity, it’s not long before that 30 KB ideal is well out of my reach. With the popularity of CSS layouts and JavaScript-enriched web page experiences, it’s not uncommon, particularly for large sites, for the CSS files alone to jump well beyond that 30KB ceiling.

But there are some principles to consider during and after you write your CSS to help keep it tight and optimized. Optimization isn’t just minimizing file size — it’s also about being organized, clutter-free, and efficient. You’ll find that the more knowledge you have about optimal CSS practices, smaller file size will inevitably come as an direct result of their implementation. You may already be familiar with some of the principles mentioned below, but they are worth a review. Being familiar with this concepts will help you write optimized CSS code and make you a better all-around web designer.

1. Use Shorthand Link

If you’re not already writing in shorthand, you’re late to the party. But fortunately, this party never ends. Using shorthand properties is the single easiest practice you can do to cut down your code (and coding time). There’s no better time than the present to start this efficient coding practice, or to review it.

Margin, border, padding, background, font, list-style, and even outline are all properties that allow shorthand (and that’s not even an extensive list!).

CSS Shorthand means that instead of using different declarations for related properties…

p { margin-top: 10px;
	margin-right: 20px;
	margin-bottom:  30px;
	margin-left: 40px; }

… you may use shorthand properties to combine those values like so:

p { margin: 10px 20px 30px 40px; }

By specifying a different number of values, browsers would interpret the rules in a specified manner, illustrated in the diagram below.

Illustration of how shorthand declarations are interpreted depending on how many values are specified for a property
Illustration of how shorthand declarations are interpreted depending on how many values are specified for a property. This order also applies to padding and border-width among other properties.

Font is another helpful shorthand property that helps save some room and keystrokes.

Illustration of font shorthand examples
Examples of the font shorthand property. Note: leaving some values unspecified will mean that those properties will reset to thier initial values.

Those are just two examples of shorthand, but by no means should be considered a comprehensive guide. Even if you are familiar with the rules above, be sure to look at the articles mentioned below for more helpful reminders of those powerful properties that help keep your code succinct. Because of the number of lines and characters saved, going from a previous version of a CSS file which used no shorthand properties to one that makes full use of shorthand can have dramatic effect on file size.

See CSS Shorthand Guide1 ( and Efficient CSS with shorthand properties2 ( for more information about shorthand properties.

2. Axe the Hacks Link

Jon Hick's blog makes use of conditional comments
Jon Hick’s blog makes use of conditional comments

Hacks against dead browsers are safe, but hacks against the living aren’t. None of them. Ever.

Keep CSS Simple4 – Peter-Paul Koch (

If you’re like me, those words from Peter-Paul Koch’s nearly 5-year-old article may make you feel a little embarrased. After all, who hasn’t served hacks to Internet Explorer 6 and even Internet Explorer 7? As bad as we may want IE6 to lay six pixels under, the truth is it’s far from dead.

But now we know that using conditional comments to serve hacks correctional declarations for IE6 and IE7 is an accepted practice, even recommended by the Microsoft IE development team. Using conditional comments to serve IE-specific CSS rules has the added benefit of serving a cleaner, and therefore smaller, default CSS file to more standards-compliant browsers, while only those browsers that need the hackery daiquri (i.e. IE) will download the additional page weight.

Here’s how to use conditional comments to serve styles only to Internet Explorer 6:

	<!--[if IE 6]>
		<link rel="stylesheet" type="text/css" href="ie6.css">

For IE7, you can use the above and substitute “6” for “7”.

Alternatively, if there is hack-less way of getting the desired result using CSS, with all other things being equal, go for it! The less hacks you have to write, the simpler and lighter the code.

3. Use whitespace wisely Link

Whitespace, including spaces, tabs, and extra line breaks, is important for readability for CSS code. However, whitespace does add, however miniscule it may be, to page weight. Every space, line-break, and tab you can eliminate is like having one less character.

But this is one area where I would not encourage you to skimp just to get a smaller file. It’s still important that you write in a way that is readable to you (and hopefully to others), and if that includes using whitespace for formatting, so be it. After all, if you can’t read it, you’re going to have a hard time applying the other principles mentioned in this article. Just be aware of the fact that whitespace is like air – you might not be able to see it, but it does weigh something.

The figure below shows two different extremes in formatting style, with much whitespace, and the other with very little. I happen to favor the single-line formatting option without tabs, as I can scan the selectors a little easier, and I develop using the full width of my wide-screen monitor. But that’s just me. You may like your selectors to appear nested, and your declarations on each line.

Illustration of two extremes in CSS formatting, one with lots of whitespace, one with little whitespace
Illustration of two extremes in CSS formatting: lots of whitespace vs. very little whitespace

Using whitespace effectively is great, and a recommended practice for easy-to-manage code, but be aware that the less whitespace you have, the smaller the file. Even if you choose work with whitespace with your working file, you can choose to remove it for the production version of your CSS file, so your files stay skinny where it really counts.

4. Prune frameworks and resets Link

Nathan Smith's 960 Grid System uses a reset
Nathan Smith’s 960 Grid System5 CSS framework uses a reset rule.

If you’ve chosen to use a CSS framework (including ones you’ve written yourself), take the time to review the documentation as well as every line of the CSS file. You may find that the framework includes some rules that you don’t care to use for your current project, and they can be weeded out. Also, you may find that the framework includes a more elegant and concise way of achieving a presentational detail than what you normally use, and knowing about them can help prevent you duplicating rule sets unintentionally.

This goes for resets as well. YUI Grid CSS6 uses a reset, and Eric Meyer’s Reset7 is also very popular. Resets are great to use because they help to neutralize a browser’s default style. But if you know the nature of the site you are building, you may find some declarations that you know you’ll never need. <pre> and <code> will likely go unused on my Aunt Martha’s recipe blog. A design portfolio probably won’t ever use <sub>, <dfn>, <var>, etc. So ditch what you don’t need. It’s not only ok, it’s encouraged, even by Eric Meyer:

As I say on the reset page8, those styles aren’t supposed to be left alone by anyone. They’re a starting point.

Crafting Ourselves9 – Eric Meyer (

Using a framework and/or a reset set of rules can help keep your work optimized, but they should not be accepted in their default state. Considering each declaration and cutting back on unneccessary ones can further help you keep your CSS files lean and readable.

5. Future-proof your CSS Link

Doug Bowman's CSS reveals specially crafted selectors used for layout
Doug Bowman’s stopdesign.com10 CSS reveals specially crafted selectors used for layout.

Another way to optimize your code is to separate layout-specific declarations from the rest of your rules. I’ve heard options of separating typography and colors from layout-specific rules in the CSS file. I’ve never been fond of this practice, as I don’t care to repeat selectors just because I have different types of declarations to associate with them.

However, I’m warming up to the idea of separating layout styles from the rest of the styles, and giving layout it’s own file, or at least it’s own section. This is also advocated in Andy Clarke’s Transcending CSS. Within the book, Clarke reminds us of the following:

Full CSS layouts have always been a compromise. The current CSS specifications were never designed to create the visually rich and complex interface layouts that modern Web demands. The current methods — floats and positioning — were never intended as layout tools.

Transcending CSS11Andy Clarke12.

One way of interpreting this is that floats and positions to establish sidebars and columns are, well, layout hacks. And though we really don’t have an alternative, we hopefully will once a layout standard is agreed upon and browsers start supporting them. When that happens, it should be easy to swap out those hacked up box-model properties for ones intended for layout. Though it will be a while before new layout modules are here, using the right properties to handle layout instead of compensating for the quirks of our current limited set of properties will most certainly help condense page weight.

6. Document your work Link

David Shea's markup guide at
David Shea’s markup guide13 illustrates the proper usage for HTML tags and how those are represented on his site, mezzoblue.com14. Even sites without dynamic HTML can have this simple and effective guide (using its own CSS file, of course!) as a starting point of documentation.

For a team of designers, it is extremely important to communicate regularly so that markup and style rules are created in a consistent way, and also to create site standards. For example, if someone comes up with way to markup a tab interface for the site, documentation will keep others from duplicating that effort, preventing code bloat in the HTML and CSS.

Documentation, including markup guides and style sheet guides, is not just for group efforts — they are just as important for a one-man design team. After all, a year after working on other things, revisiting one of your own projects can feel quite foreign. Your future self might appreciate reminder of how your CSS grid framework is supposed to work, or what pages already have a treatment for a secondary action form button, and it will save you or someone else from appending redundant and unnecessary rules to your CSS.

The choice to use documentation has a bonus side effect of being a great place to park explanations that otherwise must be included as CSS comments. CSS comments are great for sectioning off chunks of long CSS files, but verbose comments that are used to explain design choices can add to file size, and might be better suited to a markup and style guide. Documenting your code using CSS comments within your working file is most definitely better than nothing at all, but housing that material in separate documentation is a great way to keep the code focus and free from bloat.

7. Make use of compression Link

Some great applications have been created to compress and optimize CSS for you, allowing you to serve a human-unreadable but still browser-friendly files that are a fraction of the origional working copies. Applications like CSSTidy15 and the YUI Compressor16 can compress whitespace, detect and correct for CSS properties that are overwrite each other, and look for opportunites to use CSS shorthand that you may have missed. (These types of applications are excellent sources to read about, if for no other reason, to learn what things you can further do by hand).

Even popular text editors like BBEdit, TextMate, and TopStyle, can help format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP17. You can find more CSS compressors and optimizers in the post List of CSS Tools18.

It is important to note that these applications do their best to minimize errors, but they aren’t always perfect. Also, they work best when browser hacks are not included in the file set (which is yet another reason to keep those hacks external).

There is one last type of application that can help prune CSS file size I’d like to mention. It can crawl a web site and log which CSS rules and declarations are not being applied, then bring these to your attention. Unfortunately, this tool hasn’t been inventend yet, but I would gladly pay for such a application.

I can recall times when I’ve been afraid to delete certain rules because there is no documentation that explains to me that those selectors are leftover from previous iterations of development. If an app can bring those rules to my attention, that will help with maintenance and keeping CSS files lean.

Conclusion Link

Clean and optimized code is important not just for file size, but for maintenance and readability as well. The principles mentioned above are good considerations not just for CSS, but can be applied to HTML, JavaScript, and other programming languages. CSS files are not as prominent as the rendering of your web site to an end-user, but consideration of the above principles can help with both the user experience (in the form of smaller file sizes) and the developer experience (cleaner code). Apply these principles to your current and future projects, and and you will surely appreciate the efforts.

Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18

↑ Back to top Tweet itShare on Facebook

Tony White runs the one-man show Ask the CSS Guy, an after-hours blog devoted to peeking under the hood of CSS and JavaScript web-design techniques, as well as troubleshooting CSS-related problems. He resides in Memphis, Tennessee.

  1. 1

    Great tips.
    Is there a tut on how to make those awesome leaf page/code screenshots?

  2. 2

    Nice article!

  3. 3

    Great tips!

    As far as selectors that you aren’t using in the various CSS resets goes: aside from making your own, you can prune the some out and use DustMe Selectors to see if you missed any. It’s available as an add-on for Firefox.

  4. 4

    thanks again for another 5***** article! keep up good work!

  5. 5

    Shorthand is great. Totally worth learning.

  6. 6

    Your first sample

    margin-top: { 10px; }

    should obviously be

    {margin-top: 10px; }

    My personal approach for maintaining my sanity when doing CSS is to group rules not by selector, but by content. In other words, instead of

    .class1 { font-family: sans-serif; font-size: 12px; }
    .class2 { font-family: sans-serif; font-size: 14px; }
    .class3 { font-family: serif; font-size: 12px; }
    .class4 { font-family: serif; font-size: 14px; }


    .class1, .class2 { font-family: sans-serif; }
    .class3, .class4 { font-family: serif; }

    and so on. This allows you to change common properties in one place instead of hunting them down throughout the file. (CSS variables would allow a similar approach, if and when they ever get here.)


  7. 7

    Fantastic article.
    As a web developer I’ve always tried to keep my CSS and (X)HTML code to a minimum, but on tight time budgets it can sometimes be tricky to optimise.
    This is a very useful resource. Thank you.

  8. 8

    Really good article there, if everyone kept stylesheets consistent and readable then it’d be a much better place.

  9. 9

    Thanks for the neat article, I the graphics were amazing, the coding was remarkably detailed. Good job.

  10. 10

    Great article! I think I will try a CSS compressor on my next project. We’ll see how much of difference it makes!

    Thanks again!

  11. 11

    Tony, nice article. All very good tips to keep in mind, esp. documentation and removing browser hacks from your stylesheets.

    Keep it up(:

  12. 12

    With regards to 3:
    I have found this method to be very difficult when using a Versioning system like SVN as the entire line is marked as changed. I then have to compare with previous versions to find out what happened where and what caused an issue.

    Have you run into this?

  13. 13

    O.o Nice observation Bob!

    Great article! I really enjoyed the illustration. ñ_ñ

  14. 14

    It should be noted that the shorthand font: CSS property is not consistently supported across all the major browsers. For instance, I know that Safari has an issue with the line-height portion of the shorthand.

    I would recommend to others that the font: shorthand be avoided to ensure greatest cross-browser compatibility.

  15. 15

    Checkout CSSZENMASTER.COM. It’s gonna be a tight site about css coding.

  16. 16

    Great article, very informational.

  17. 17

    WOW kids Stuff, Please write something for more pro.

  18. 18

    Nice article, though I knew all of these thing before…

  19. 19

    Yes Roman, everyone knows what you know and you are paying money to see the content on this website.

  20. 20

    excellent article *****

    there is no voting ??

  21. 21

    I ‘ve got a problem with CSS: all sites have similar layouts (i.e. right in the middle), they look so boring.

  22. 22

    You said:

    There is one last type of application that can help prune CSS file size I’d like to mention. It can crawl a web site and log which CSS rules and declarations are not being applied, then bring these to your attention. Unfortunately, this tool hasn’t been invented yet, but I would gladly pay for such a application.

    Get your money out!
    Dust-Me Selectors, a Firefox extension from James Edwards.

    It extracts all the selectors from all the stylesheets on the page you’re viewing, then analyzes that page to see which of those selectors are not used.

  23. 23

    Using conditional comments for different browsers is a good way.
    But there are also the “simple hacks” like:

    /* IE 6 */
    * html .class {
    attribute: ie-property;

    If these are commented they could replace conditional comments.
    Of course the hackless way is always the best as you describe ^-^

  24. 24

    Does tips sure seem useful and u did use some very cool images there.

  25. 25

    This is a nice article – for the website I work on we have taken some of these a step further.. Using an Apache Perl handler we merge together multiple CSS files (on server start-up) into a readable CSS file for development and then a “single-line” minified CSS file for production. This allows (a) good documentation – each individual file has comments documenting all the CSS in it; (b) compartmentalisation – each CSS file has it’s own specific purpose; (c) easy re-development of one section of the CSS – to switch in and switch out styles.

  26. 26

    Great article, thanks for that.
    At my last work I descovered a very nice methode of commenting “areas” in CSS. This is how I do if I want to seperate several areas like “content”, “footer” etc.:

    ================================================================================ CONTENT #

    The big advance is: If u scroll down the document very fast to reach a point, u will see and identify the area-descriptions light-fast, cause they are at the far right and in uppercase =) So instead of using F3 and type in a search, I seperate my CSS in areas find tags within 2 seconds. Cheers from Germany and sorry for my bad English.

  27. 27


    That’s not a problem with CSS, that’s a problem with cookie-cutter designers and a lack of imagination. I blame the WordPress generation!

    For some great inspiration, checkout High Floater.

  28. 28

    Good article but a little bit paranoid :)

  29. 29

    Nice article, just thought I’d add one observation, I’ve found that the IE conditional comments will sometimes not work unless the comment and the first line of code are next to each other.

    No idea what causes this though, something to do with whitespace I suppose.


  30. 30

    Excellent article. I don’t think we can be reminded too frequently of many of the topics covered here.

  31. 31


  32. 32

    Excellent article but the illustrations really are superb – congratulations!

  33. 33

    Paranoid? Are u nuts? Have you ever had to scroll through a 2000+ line stylesheet? Obviously not!

    Always keep you code tidy and split it into bits and describe them or your code will be doomed as soon as you need to do changes after a month or so.

  34. 34

    O, and the illustrations are awesome indeed!

  35. 35

    @ Jackson Hyde: Hm, I can’t totally agree. Yes, “the wordpress generation” tends to f*** on style and own creations – just take one of 1000 themes and that’s ur “own” page. The question is if this is caused by WordPress itself or the system WordPress is based on – CSS, XHTML, PHP – ? I mean, WordPress does bring those three to perfection (in one kind of way) … the result is a never reached simplicity for people who never would have thought of publish in the internet 7 years ago. Means: The creative ones, those with imagination, aren’t vanished – they just don’t carry weight that much anymore in the internet. And aslong Flashsites aren’t reachable for SEs, creativity and imagination will be imprisoned by the rules of CSS and so on if u want to reach many people. Check my page out, hundred hours in PS and a lot of imagination, but in the end again an regular-like layout… in Flash it could be a badass-page!!

  36. 36

    hey there. I thought it could be cool to share those posts i wrote a while ago. Sorry but it’s french :p

    CSS with object oriented approach :
    IE6 png transparency hack :

  37. 37

    nice. i keep forgeting the shorthand property for “font”.

  38. 38

    I am also interested by the same pageflip screenshot…
    How about a tut regarding this ?

  39. 39

    Gzipping using PHP is dangerous, because PHP doesn’t send proper cache headers (in fact, it may send complete garbage in tune of no-cache-never-ever).

    mod_gzip/mod_deflate is better.

  40. 40

    @Paul Frost and @RickFu:

    I had no idea about the “Dust-Me Selectors” firefox extension. I’ll have to give it a whirl. However, it states that it checks everything on the current *page* – I still think there is a market (that includes me) for an app that checks everything on the *entire site* (without me having to view each page of the site using this extension).

    @Bob Myers:

    Good catch – and my bad! What was I thinking?! I’ll write Vitaly to get him to correct it.

  41. 41


    I think you misunderstood me a little, I’m a big fan of WordPress, it’s a great little CMS and as you say, a perfect marriage of PHP, CSS and XHTML.

    The problem is that a lot of people don’t seem to be able to break out of the blog format (two or three column layout, right hand nav etc). It’s a perfect format for blogs, but for different types of site I think that a lot more can be done. I’m guiilty of resorting to a WordPress template myself when time is short and I need something that looks half decent.

    I guess it’s like any design trend, sooner or latter it stagnates. I just want to see some innovation.

    PS. I posted a link to High Floater because it collects a lot of really beautiful sites (mostly XHTML)- I myself wouldn’t build a whole site in Flash (although this does depend on your target audience). And for the record, Google and Adobe are working on the Flash SEO thing, textual content in Flash is now indexed – Link

  42. 42

    Good article with useful information… But I agree with previous posters. A tutorial on your page turn graphic over the code would be awesome. I think that this is the first time I’ve seen code illustrated this way – clever!

  43. 43

    @Jackson Hyde #27

    Fantastic link!!!
    Cheers for that!

  44. 44

    “The current mehtods – floats and positioning – were never intended as layout tools.”

    Should be “methods”

  45. 45

    Also, I prefer to use several css files and load them into the page as one through a PHP file. It just helps organize the code better.

  46. 46

    I couldn’t agree more about not using hacks. I actually don’t even fine a use for conditional comments most of the time either. If it’s between getting something a couple pixels closer in IE by using a conditional or just not bothering I would probably go for the latter. At the end of the day no one is going to notice something with 6 pixels of padding rather than 8 pixels and my code is cleaner and more easily managed later because of that.

    Also, regarding using CSS resets I’m a big fan of generating your own reset to use in new sites rather than picking up someone elses. 9 times out of 10 50% or more of a prebuilt reset is just not needed. I have one simple one I’ve copme up with that I add to if need be on a site by site basis.

    Great article, simple and fast to read and I really enjoyed the visuals you provided with it.

  47. 47

    great article…
    simple, clear… I’ve learn some things here…


  48. 48

    For those who recommended the Dust-Me Selectors firefox extension, I thought it was only for the page you are viewing, but it says it can crawl an entire site. That’s what I was looking for! I can’t wait to see how well this works.

  49. 49

    very nice article, thank you

  50. 50

    No doubt about it, CSS style sheets make very attractive websites. Much better than anything else currently on the market. Making them clean though is the key!


↑ Back to top