7 Principles Of Clean And Optimized CSS Code

Advertisement

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

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 Guide (dustindiaz.com) and Efficient CSS with shorthand properties (456bereastreet.com) for more information about shorthand properties.

2. Axe the Hacks

Jon Hick's blog hicksdesign.co.uk/journal makes use of conditional comments
Jon Hick’s blog hicksdesign.co.uk/journal makes use of conditional comments

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

Keep CSS Simple – Peter-Paul Koch (digitial-web.com)

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">
	<![endif]-->

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

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

Nathan Smith's 960 Grid System uses a reset
Nathan Smith’s 960 Grid System 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 CSS uses a reset, and Eric Meyer’s Reset 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 page, those styles aren’t supposed to be left alone by anyone. They’re a starting point.

Crafting Ourselves – Eric Meyer (meyerweb.com)

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

Doug Bowman's stopdesign.com CSS reveals specially crafted selectors used for layout
Doug Bowman’s stopdesign.com 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 CSSAndy Clarke.

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

David Shea's markup guide at mezzoblue.com
David Shea’s markup guide illustrates the proper usage for HTML tags and how those are represented on his site, mezzoblue.com. 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

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 CSSTidy and the YUI Compressor 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 PHP. You can find more CSS compressors and optimizers in the post List of CSS Tools.

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

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.

↑ Back to top

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?

    0
  2. 2

    Nice article!

    1
  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.

    0
  4. 4

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

    0
  5. 5

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

    0
  6. 6

    Shorthand is great. Totally worth learning.

    0
  7. 7

    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!

    0
  8. 8

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

    Keep it up(:

    0
  9. 9

    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; }

    use


    .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.)

    Bob

    1
  10. 10

    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?

    0
  11. 11

    O.o Nice observation Bob!

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

    0
  12. 12

    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.

    0
  13. 13

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

    -1
  14. 14

    Great article, very informational.

    0
  15. 15

    WOW kids Stuff, Please write something for more pro.

    -1
  16. 16

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

    0
  17. 17

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

    0
  18. 18

    excellent article *****

    there is no voting ??

    0
  19. 19

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

    0
  20. 20

    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.

    0
  21. 21

    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 ^-^

    0
  22. 22

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

    0
  23. 23

    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.

    0
  24. 24

    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.

    0
  25. 25

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

    0
  26. 26

    Great article, thanks for that.
    At my last work profiterror.de 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.

    0
  27. 27

    @jeanmarc

    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.

    0
  28. 28

    Good article but a little bit paranoid :)

    0
  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.

    Cheers.

    0
  30. 30

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

    0
  31. 31

    HEY MAN THIS WAS WICKED!

    0
  32. 32

    Excellent article but the illustrations really are superb – congratulations!

    0
  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.

    0
  34. 34

    O, and the illustrations are awesome indeed!

    0
  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!!

    0
  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 : http://blog.martian-arts.org/?p=22
    IE6 png transparency hack : http://blog.martian-arts.org/?p=23

    0
  37. 37

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

    0
  38. 38

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

    0
  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.

    0
  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.

    0
  41. 41

    @profiterror

    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

    0
  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!

    0
  43. 43

    @Jackson Hyde #27

    Fantastic link!!!
    Cheers for that!

    0
  44. 44

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

    Should be “methods”

    -1
  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.

    0
  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.

    0
  47. 47

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

    CPG

    0
  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.

    0
  49. 49

    very nice article, thank you

    0
  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!

    0
  51. 51

    All these are good accept for:

    3. Use whitespace wisely

    readability is far more important than “page weight” seeing that you can add gzip compression and several other techniques after the fact. Please stop encouraging people to write CSS like in your example, it’s barely readable, and a pain to maintain.

    0
  52. 52

    Usefull article.

    0
  53. 53

    Definately a good read to end the working day – bookmarked!

    For someone who can make a half decent site using HTML and CSS, its nice to find a clean straightforward article, highlighting useful tips. Thank you for sharing this.

    0
  54. 54

    I actually use the CSS Redundancy Checker, a Ruby script that looks over a list of URLs and gives a report of dead declarations. It’s quite handy, and while not a perfect tool, it’s open-source and so you could easily port this over to other languages and maybe even use JS to do it. See http://ajaxian.com/archives/css-redundancy-checker for the details.

    0
  55. 55

    Thanks: I’m sitting here with BBEdit and haven’t flicked it at my CSS files yet. Next? (I think I saw a line-height in there…)

    0
  56. 56

    Great article. I have so many bad CSS habits. Reading this makes me want to be a good boy.
    Also, thanks to those posting link to / comments about Dust-Me Selectors

    0
  57. 57

    @rob

    Regarding your comment that states:

    “All these are good accept for:
    3. Use whitespace wisely
    readability is far more important than “page weight” seeing that you can add gzip compression and several other techniques after the fact. Please stop encouraging people to write CSS like in your example, it’s barely readable, and a pain to maintain.”

    Rob, it sounds like you briefly scanned the article instead of reading it, otherwise you wouldn’t seen this part of the whitespace section:

    “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.”

    As you can see, we’re more in agreement than what you gave me credit for. I state that the user just be *aware* of what happens with whitespace, then I encourage people to write in a way that is most readable to them.

    I’m up for criticism and corrections, but that feedback is most valuable to me and others if the critic has read the entire article.

    0
  58. 58

    sd (August 18th, 2008, 3:58 pm)
    Great tips.
    Is there a tut on how to make those awesome leaf page/code screenshots?

    PS CS3 > Transform > Warp – pull bottom left corner.

    0
  59. 59
  60. 60

    thats just simple photoshop you idiot

    -2
  61. 61

    Awesome article, I needed to get back on track and this was a good nudge. Articles like this are why I read Smashing.

    0
  62. 62

    Tips on short css files:
    1. Code the files with tabs, spaces and everything. Get thing sorted out properly. Bug fix.
    2. Find a Css compressor online and make a second CSS file with no tabs, spaces or comments.
    3. Upload both files to your sever and use the compressed file. Then add a comment to the uncompressed file so people can view it.
    4. Then you have an easy understandable and changable version, and a lightweight one to serve the browsers.

    0
  63. 63

    Nope. Wrong. Buzz. Try again.

    Anyone, ever, who makes any argument based on keystrokes or “amount” of code loses. Period. Even on a level along the lines of: programmers are supposed to be logical folk. You are saving pennies to waste Cnotes. Code is written **once**, it is read many, many times. The keystrokes you invest once will pay off numerous times over.

    You actually recommed less white space. YECK!!!
    Please, please, please can we start churning out coders who…well, want to code??!?!

    I just don’t get how so many people don’t get this:
    Source code is not for the computer. Source code has nothing to do with the computer. If we gave a rip about the computer, we would be writing 1s and 0s. The express purpose of higher level languages is to get the darn machine out of the mix. From the beginning, source code was made for humans. The first thing the box does is turn you silly human-nonsense into ‘meaningful’ instructions.

    Doing anything in your code that depletes the human value (as long as you aren’t creating bad code, that is the trump card) of your code is bad, bad, BAD!!!

    Kinda sad because there are some other very good suggestions here.

    -1
  64. 64
  65. 65

    @gh0st:

    I actually didn’t recommend less white space.

    Read the article before you poo-poo on it.

    0
  66. 66

    hey gh0st,

    we’re all very happy you managed to learn something about *compiled* code. Which is that whitespace rarely matters. However, it’s not the same in CSS. Maybe you should get a clue before berating the author. Removal of *unecessary* whitespace is important in CSS for file size.

    0
  67. 67

    Unfortunately shorthand is not accepted by everything. A lot of older browsers may not recognize shorthand because they work from a different version of CSS. Also, writing certain elements in shorthand such as “font” may not validate. Although a lot of these tips are good for cleaning and organizing your CSS sometimes you have to make a sacrifice to meet full compatibility across all browsers and if you really care about validation – that too. Compression is useful if you are completely done with your stylesheet, because a lot of “compression” type tools may completely rewrite entire sections of your stylesheet reversing all your work (if you didn’t make a backup) that you did for personal reasons (like comments, some tools take them out entirely). One thing I do agree with is separating your stylesheets, and has always been a good practice in my opinion. Instead of trying to edit one big stylesheet you can easily change sections of CSS code on the fly without having to use the Find option and hope for the best. Use of white space to properly nest and present your CSS code to other developers is also a plus, but honestly if you are the only one to ever use the stylesheet and know where everything is you can save precious bytes by formatting it however you want.

    0
  68. 68

    Great stuff as usual!!

    0
  69. 69

    You be broken yes?

    0
  70. 70

    Ohhhh!!!! You no be broken!!!!!

    0
  71. 71

    excelente articulo, sobre toda la parte de comentarios condicionales.. rulz! gracias.

    0
  72. 72

    I don’t believe Andy Clarke is entirely correct when he says “The current methods — floats and positioning — were never intended as layout tools.” Especially when there are things like the Visual formatting model in the spec from 1998. Obviously the intention was there to create something that could be used for layout/visual formatting. Maybe they didn’t intend on floats being used in that way, but positioning? What else would you use it for but the layout of elements on a page? And I believe we may be nearing a time when we can switch from floats for layout to fixed positioning.

    And I still totally disagree with axing the hacks. It’s site/project dependent. Sometimes it’s just a few simple hacks, and weighing that over the additional server calls/load for IE specific stylesheets makes a difference on larger sites. There are already enough additional files served specifically to IE such as PNG fixes, etc., so it should be a consideration, not a rule.

    0
  73. 73

    If the true aim of this article is to show the 7 main principles of clean and optimized css then quite a few things have been missed. Perhaps the main aim was to promote the writers site or to get to the top of digg???

    For example …

    Step 7 will automatically do step 1 so why mention both. http://www.cleancss.com/ which is based on CSS Tidy mentioned above will not only find any inefficient “long-hand” as well as a bunch of other great tricks for compressing css. Be warned though it almost always breaks your layout so it is best used for spotting.

    Step 4 – prune resets. Why not get rid fo them all together by learning what attributes are automatically included with XHTML elements and only nullify the ones you don’t want?

    Why leave out possibly the greatest way in which CSS can be optimizes: Make use of inheritance. Try setting important XHTML selectors like font and a for your entire site ONCE at the very top of your style sheet and letting them flow through the whole site.

    Try only having one style sheet and grouping elements under a small number of ids like #divFooter and #divNavigation and then directly targeting your XHTML elements through those ids to avoid adding classes to your XHTML and CSS i.e. #divFooter {styles for the footer} #divFooter strong {styles for anchors in the footer} #divFooter strong {styles for strong elements in the footer}. You will be surprised how few classes you really need!

    0
  74. 74

    Nice article!

    but// How much can white space really add to a css file? Surely on 90% of sites, and 90% of connections, a few 100 bytes isn’t going to be noticable? Much better to be able to read the stuff.

    0
  75. 75

    Some was good but most was just cut and pasted from the guys who wrote the best books on this subject.
    Nothing really new.

    0
  76. 76

    wow, great posts as per normal ;)

    0
  77. 77

    Hi. What’s that monospaced font shown in the screenshots for items (2), (4) and (5)? Thanks. :)

    0
  78. 78

    Write the css in whatever the way you want. Just go to this url (http://teenage.cz/acidofil/tools/cssformat.php) it will compress and format and throw it to you. Finish!

    0
  79. 79

    “hacking is ok says the Microsoft team” … ok so now that they said it … LOL

    … in other words “it’s ok to patch our bad browsers” …

    nice article… nuthing new…

    0
  80. 80

    Great tips — but an important typo:


    the end of the conditional statement must have one more square bracket before the ‘endif’ and the entire line should read as follows:
    White space matters in these too. In the above chain, the first statement, as far as IE is concerned, is never terminated, so IE7 thinks the contents of the entire page is conditional to IE6 only. Needless to say, that can be something that takes a lot of head scratching to sort out, if you’ve never seen it before.

    0
  81. 81

    The author did have a very creative writing style that he used. It was humorous in several places.

    Here is one more thing I will say about it…

    He calls CSS layout positioning a layout hack and then follows up with this…

    “And though we really don’t have an alternative, we hopefully will once a layout standard is agreed upon and browsers start supporting them. ”

    This is why I believe that things like WPF, Silverlight and Flash are far superior constructs and the web should be for service data transfer only. I am sick of waiting for standards commitees to agree on something that is only going to be inferior once it does surface anyway, like the removal of the document.all collection from so called “standards compliant” javascript. Referring to an object as a literal is far better than referring to an object by string. What OO guru would argue with that? What a ridiculous pile of crap they have turned javascript into.

    If we want real solutions for those problems now instead of hacks like we all must do on a daily basis, then we need to turn to properitary standards made my Microsoft and Adobe. What the heck has the w3C been doing over the past 10 years anyway? Anything other than arguing amongst themselves and redefining proprietary standards that worked fine to begin with? I am probably speaking much farther than I should because I don’t really know, but from what I understand the w3c is a bunch of losers and I have been frustrated with them for far too long.

    Abandon the web as we know it and give me propreitary standards that actually work as intended instead!

    0
  82. 82

    I use the same formate for css as you said in your article Coooool tips for css optimization but can u tell me the clear solution for white space?

    0
  83. 83

    Idiot? Let the flamewar begin….

    0
  84. 84

    this is a truly SMASHING article

    0
  85. 85

    hmm… nice article. Very useful

    0
  86. 86

    Thanks! Visit my web site!

    0
  87. 87

    Nice and clean css coding styles.

    0
  88. 88

    May I know how to make the code typography like in your site? It’s so unique and beautiful. Thanks.

    0
  89. 89

    Being new to this, I just wanted to say tanks for the great article, I do have some questions…

    1) How do you know what works and does not work in IE6+7? Do you build the site and then just find out in testing? Or is there a ‘list’ or things that dont work for sure?

    2) The page curl screenshots are cool! I have seen ‘real’ page curls on come css sites. Does anyone know how this is done?

    cheers again.

    0
  90. 90

    Most PC machines I have put to trash had a HD with CSS personalizing in IE – sound like ya’ folks are in Sahara at work on CSS ‘cos there is not any code apart from IE where the user has a positive way not to see what some authors – now this pp looks lovely – some authors have placed a nasty direction to web development ever since it got out on the shop with Windows 95 – a lovely code too – while you work for the void space of users I will go on using stolen FBI browser to please a growing number of hackers out there – no problem of yours?

    0
  91. 91

    whats the font for the css code there?
    http://88.198.60.17/images/clean-optimized-code/figureD.jpg

    and awesome article, quite helpfull =)

    0
  92. 92

    Great tips. Thanks

    0
  93. 93

    Congrats on the mention on boagworld,

    0
  94. 94

    When your css files are gzipped by your webserver, this kind of “optimization” is not worth it.

    0
  95. 95

    Good tips except for the white space optimization. This makes such a marginal difference that it simply is not worth destroying the readability of you code. Does everyone realize how fast a even a low end computer parses through CSS files? We are talking about tiny fractions of a second here. Even if you had a ridiculous amount of CSS, let’s say 5000 lines, you could never tell a difference. If this really is a legitimate concern, why not remove all formatting from your HTML document too? That would really speed things up. Please people, write readable code, not code that will be parsed 0.0002 seconds faster.

    0
  96. 96

    You forgot a major method for leaner CSS, namely:
    Learn how the cascade works and employ it!

    All bloated stylesheets one encounters have a major ID-entity crisis coupled with a raging Class-war – mainly due to bad or non-use of the cascade.

    Remember – the things are called **Cascading** Stylesheets after all.

    0
  97. 97

    Nice Tips for new beginner on CSS ;)

    0
  98. 98

    Hello、I am a specialized CSS editor

    0
  99. 99

    This is an EXCELLENT post. I actually summarized it into main points and printed a copy for reference. I think it is very easy to miss out some of these points. By using it as a checklist, I found that the more I refer to it, the more optimized my CSS is becoming.

    Great post guys ! Keep up the good work !

    0
  100. 100
  101. 101

    Wow, thanks for informations

    0
  102. 102

    great article…simple, clear —————–thanks……..

    0
  103. 103

    What a great article it is. A better place for a beginner to understand.

    0
  104. 104

    Thanks for the nice job

    0
  105. 105

    thank you!

    0
  106. 106

    good article,but I hope there will be a tool can process all the things above,hehe,^_^

    0
  107. 107

    thx a lot it’s very intersting ;)

    0
  108. 108

    One principle I always try to follow to keep my code clean is DRY – as in “Don’t repeat yourself”.
    I published a few tips on my blog to keep your CSS styles DRY

    Refactoring your CSS styles to comply with the DRY principle

    0
  109. 109

    coool……
    that was simple but greate and useful.
    and greate samples.

    0
  110. 110

    I must say “Thank you” to you for this post.
    I found it when I was looking for way to optimize CSS.
    I’ve wondering about it.

    0
  111. 111

    THANKS

    0
  112. 112

    great tips!

    THANK YOU!!!!!!!!!!!!!!!!!!!!!!!!

    0
  113. 113

    it’s cool.

    0
  114. 114

    This is a great tip and tutorial to help us move forward into the future of web design standards.

    0
  115. 115

    Great tips. Nice Article THANKS!

    0
  116. 116

    Great tips thanks a lot. Speaking about css compression – just found a tool that you actually can use online by just entering a url or uploading CSS or JS files that you want to merge, compress, gzip – pretty easy to use check it out at http://www.zbugs.com

    0
  117. 117

    Nice and informative, I suggest there must be list of 7 principle at the start so that we can remember these rules at first glance. However, the post is wonderful. I have noted the seven Principles. Thanks for such good post.

    0

↑ Back to top