How to Micro-Optimize Your CSS
Posted on June 21, 2010 in Optimization by Jeff Starr
There are many ways to optimize your web pages. In addition to reducing HTTP requests and delivering compressed files, we can also minify code content. The easiest way to minify your CSS is to run it through an online code minifier, which automatically eliminates extraneous characters to reduce file size. Minification shrinks file size significantly, by as much as 30% or more (depending on input code). This size-reduction is the net result of numerous micro-optimization techniques applied to your stylesheet. By learning these techniques and integrating them into your coding practice, you’ll create better-optimized CSS during the development process. Sharper skills, cleaner code, faster downloads – it’s a “win-win” for everyone.
In this Perishable Press article, you’ll learn how to write leaner, cleaner CSS using 10+ micro-optimization techniques..
The basic idea behind micro-optimizing your CSS involves writing clean code, eliminating extraneous characters, and reducing overall file size. And you don’t have to rely on an automated script to do everything for you. Instead of writing lazy, sloppy, bloated code and then just dumping your hideous CSS into an automated minifier, it’s better to understand and practice as many micro-optimization tips as possible, given your particular coding style and specific project requirements.
I doubt that anyone is going to use all of the micro-optimization techniques presented in this article. If you did, your code would look like you ran it through a minifier, something like this:
#comments ol{margin:10px 0 20px 25px}
#comments ol li{margin:7px 0 7px 25px;width:90%}
#comments .comment ol,#comments .comment ul{margin:3px 0 10px 5px}
#comments .comment ol li,#comments .comment ul li{margin:5px 0 5px 25px}
#comments #comments-closed{margin:5px 0 15px 15px}
#comment-policy{margin:5px 10px 0 0;width:300px;float:right;clear:both}
#comment-policy span{font-family:Monaco,"Panic Sans","Lucida Console","Courier New",Courier,monospace,sans-serif}
#comment-form{padding-top:10px;margin-top:15px}
#comment-form fieldset{border:0 none}
#respond #comment-form p{margin:0 0 0 20px}
#comment-form div.input,#comment-form div.textarea{border:1px solid #CF7400;float:left;clear:both;margin:0 0 10px 20px}
#comment-form div.textarea{height:221px;width:470px}
#comment-form textarea{height:211px;width:460px}
#comment-form input,#comment-form textarea,#comment-form #submit{font-family:Verdana,Helvetica,Arial,sans-serif;border:1px solid #A6945E;background:#291F16;font-size:11px;color:#A6945E;padding:4px;margin:0}
#comment-form #submit{background:#3B2E22}
#comment-form input:focus,#comment-form input:active,#comment-form textarea:focus,#comment-form textarea:active,#comment-form #submit:hover,#comment-form #submit:focus,#comment-form #submit:active{border:1px solid #FFC;background:#3B2E22;color:#cc9}
#comment-form #comment-info{padding:0 0 15px}
That’s about as optimized as it gets, but you don’t want to work with code that looks like that. Fortunately, it’s not an “all-or-nothing” scenario. Think of micro-optimization as a hypothetical spectrum, with completely minified code at one end, and completely “un-minified” code at the other. As designers, we each place differently along the spectrum, with each person’s CSS reflecting their ability to write clean and well-optimized code. All of this of course is completely subjective – it’s up to you as a designer to develop your own coding strategy using as many (or as few) of these micro-optimization techniques as desired.
The goal of this article is to introduce you to the many different ways of micro-optimizing your stylesheets, enabling you to write leaner, cleaner CSS. While every technique is effective, not all of them are going to be practical during the development process. Use what works. Even if you ignore these techniques and just crank out your code through a minifier, this article will help you understand micro-optimization and how the process of minification works.
Tip #1: Use the shortest possible color values
For properties where color is used, use the shortest value possible. For example, let’s say you want a white background applied to the <article> element. You could write something like this:
article { background-color: rgb(255,255,255); }
That works, certainly, but we can do better:
article { background-color: #ffffff; }
That’s good, but we can use the shorthand format for certain color values:
article { background-color: #fff; }
Nice. But look at that background property – there is no need to write it all out like that. Instead, just use this:
article { background: #fff; }
So let’s compare the “before” and “after” for this example:
article { background-color: #ffffff; }
article { background: #fff; }
A significant improvement. Also note that certain color names are shorter than their hexadecimal representations. For example, writing “red” is more efficient than “#cc0000”.
Tip #2: Merge duplicate properties
After you have completed your stylesheet, take a moment to scan for duplicate properties and merge them. You could do this manually, or for longer stylesheets you can use an online CSS optimizer to automate the process. Either way, the goal is to reduce the amount of code used in your stylesheets by eliminating redundant properties, values, and declarations. As a simple example, let’s say you discover the following rulesets in different locations in your stylesheet:
p {
font-family: Georgia, serif;
font-weight: normal;
line-height: 1.33em;
font-size: 1.22em;
}
.
.
.
p {
font-family: Georgia, serif;
font-weight: normal;
line-height: 1.33em;
font-size: 1.33em;
}
In this order, the latter rules will be applied and the first ignored, so you might as well combine the properties to save a few bytes:
p {
font-family: Georgia, serif;
font-weight: normal;
line-height: 1.33em;
font-size: 1.33em;
}
Granted, duplicate properties are usually more subtle and complicated than this example, but the idea is clear: eliminate redundant properties by combining them into one. On the page, your design is going to look the same, but behind the scenes you’re delivering the stylesheet faster, using fewer resources.
Tip #3: Use shorthand syntax whenever possible
I bet some of you were virtually screaming during the previous example: “combine the properties using shorthand!!” And rightly so, but using CSS shorthand is important enough to warrant a tip all its own.
The idea with CSS shorthand syntax is that you can consolidate certain properties into a single declaration. Let’s return to the previous example:
p {
font-family: Georgia, serif;
font-weight: normal;
line-height: 1.33em;
font-size: 1.33em;
}
That’s a lot of code, and if you’re writing everything out like that for other selectors as well, your stylesheet could quickly inflate with all sorts of bloat. Here is our ruleset after consolidating the declarations via shorthand:
p {
font: normal 1.33em/1.33 Georgia, serif;
}
Much, much better. There are actually quite a few properties that may be combined using shorthand syntax. Here are a few more examples:
/* these 4 properties */
background-color: #fff;
background-image: url(i/dope.png);
background-repeat: repeat-x;
background-position: 0 0;
/* can be written as */
background: #fff url(i/dope.png) repeat-x 0 0;
/* these 4 properties */
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
/* can be written as */
margin: 10px 20px 10px 20px;
/* these 3 properties */
border-width: 1px;
border-style: solid;
border-color: red;
/* can be written as */
border: 1px solid red;
Hopefully these are self-explanatory. If not, check out these fine articles. The goal here is to encourage you to use these shorthand rules.
Tip #4: Combine similar numerical values
Looking at the previous example, we see another case where micro-optimization is possible. Consider the following:
margin: 10px 20px 10px 20px;
For properties such as margin and padding that allow for multiple numerical values, we can save bytes by combining them:
margin: 10px 20px;
This rule is equivalent to the previous example, where 10px sets the margin for the top and bottom, and 20px sets it for the right and left. If all four sides were the same, we could simplify even further:
margin: 10px;
Keep an eye on this. There are numerous properties for which this shorthand may be applied. And it certainly helps shave off the weight.
Tip #5: Omit extraneous zeros
This one is subtle, but the savings can add up. When you write numerical values, do not include any extraneous zeros. For example:
padding: 0.1em;
margin: 10.0em;
You really don’t need those extra zeros, so wipe them out:
padding: .1em;
margin: 10em;
In the second line, we also killed the period, which is unnecessary for whole numbers. Remember, these are micro-optimization techniques, meant to provide cumulative savings on file-size, bandwidth, and server resources. Incremental changes produce an overall optimizing effect. Just sayin.
Tip #6: Omit units for zero-values
This is a no-brainer, but something that took me about a year to fully appreciate and embrace. Consider this:
padding: 0px;
Looks harmless enough, but there are two extra characters that don’t need to be there. When it comes to zero values, you don’t need to specify the unit. Zero somethings is still zero, nothing, nada. Just use zero and forget about it:
padding: 0;
Significant? Next time you’re digging around in your stylesheet, count up all the zero-values and multiple the total by two – that’s how many characters we are saving for each file load.
Tip #7: Omit the last semicolon
Did you know that the last semicolon in every ruleset can be omitted? It’s true, there is no need to include it. Let’s return to our paragraph example:
p {
font-family: Georgia, serif;
font-weight: normal;
line-height: 1.33em;
font-size: 1.33em;
}
The last declaration block in any ruleset does not require the closing semicolon. So we can write this:
p {
font-family: Georgia, serif;
font-weight: normal;
line-height: 1.33em;
font-size: 1.33em
}
..and then further optimize the code via shorthand notation:
p { font: normal 1.33em/1.33 Georgia, serif }
To me, it still looks weird not including the semicolon, and in fact, most of the designers I study do in fact include the last semicolon pretty much for every ruleset. Would love to hear your opinion on this.
Tip #8: Remove comments from production files
Yes, CSS comments are essential to maintaining a clean and well-organized stylesheet, but they are 100% useless to browsers. So why include them in your production files? To the browser, all of those carefully placed comments are literally completely ignored, even though they continue to consume valuable server resources, bandwidth, and download time. So get rid of ‘em!!!
If this sounds like blasphemy to you, relax. I explain how to enjoy the best of both worlds at the end of this article.
Tip #9: Remove unnecessary whitespace
Remove as much whitespace as possible. Except for a few shorthand cases, it’s simply not necessary and bloats your code by as much as 50% or more. Let’s look at an example. Here we have a typically styled body selector:
body {
font-family: "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background-color: #333;
text-align: center;
margin: 0px auto;
font-size: 62.5%;
color: #FFF;
}
Removing the needless whitespace, we get this:
body{font-family:"Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;text-align:center;background:#333;margin:0px auto;font-size:62.5%;color:#fff}
13 spaces and 8 line breaks were removed from this ruleset. Seem pointless? Consider this: if we have 50 (a modest number) selectors in our stylesheet, each averaging 10 spaces, we have over 500 characters that can be removed. That’s over 500 bytes per file load, which is cumulatively significant for sites with any considerable amount of traffic.
Note that there are property values that must include whitespace in order to operate. Properties condensed into shorthand notation are a good example, as seen here:
p {
font:normal 1.33em/1.33 Georgia,serif;
}
See how the whitespace is used to differentiate between the different values? Whitespace can be removed from between the property-name and the first proerty-value, but it needs to be there between the values themsleves. Here is what it would look like if we removed all of the whitespace:
p {
font:normal1.33em/1.33Georgia,serif;
}
Obviously, this isn’t going to make any sense to the browser, and the rule will be ignored (although IE may do something with it).
And of course, all of this brings us to our next and final micro-optimization tip:
Tip #10: No code-folding shenaniganz!
If there is one thing I enjoy, it’s formatting my CSS with all sorts of elaborate folds, tabs, and spacing. I like to make it look pleasing to the eye. None of this efficient single-line stuff. Unfold it, tab it in, and make it look hot. Here is a hearty example of how I am folding and formatting my code these days:
hr {
margin: 25px 0 25px 0;
background: #CF7400;
text-align: left;
padding: 15px 0;
display: block;
border: 0 none;
color: #CF7400;
height: 1px;
clear: both;
width: 96%;
}
acronym, abbr {
border-bottom: 1px dotted #514031;
cursor: help;
}
ins { text-decoration: underline; }
del { text-decoration: line-through; }
sup {
font-size: 10px;
line-height: 0;
color: #cccc99;
}
em { font-style: italic; }
small { font-size: 10px; }
strong { font-weight: bold; }
strong:target, h3:target, h4:target {
background: #CF7400;
padding-left: 25px;
}
code, kbd, samp, tt, var {
font-family: "Courier New", Courier, monospace, sans-serif;
color: #cccc99; /* #cc9933 #cccc66 #cccc99 */
font-size: 11px;
}
h3 code { font-size: 13px; }
pre {
border-left: 1px solid #CF7400;
padding: 10px 0 12px 10px;
background: #3B2E22;
overflow: auto;
margin: 25px 0;
width: 525px; /* 95% of 555px = 525px */
}
pre:hover {
border-left: 1px solid #FFFFCC;
background: #3B2E22;
}
Just look at all that pointless folding and formatting! It’s a crying shame, as far as optimization goes. A far more efficient way of writing the same CSS looks like this:
hr { background:#CF7400;margin:25px 0;text-align:left;padding:15px 0;display:block;border:0 none;color:#CF7400;height:1px;clear:both;width:96%; }
acronym,abbr { border-bottom:1px dotted #514031;cursor:help; }
ins { text-decoration:underline; }
del { text-decoration:line-through; }
sup { font-size:10px;line-height:0;color:#cc9; }
em { font-style:italic; }
small { font-size:10px; }
strong { font-weight:bold; }
strong:target,h3:target,h4:target { background:#CF7400;padding-left:25px; }
code,kbd,samp,tt,var { font-family:"Courier New",Courier,monospace,sans-serif;color:#cc9;font-size:11px; }
h3 code { font-size:13px; }
pre { border-left:1px solid #CF7400;padding:10px 0 12px 10px;background:#3B2E22;overflow:auto;margin:25px 0;width:525px; }
pre:hover { border-left:1px solid #FFC;background:#3B2E22; }
See, no crazy folding shenaniganz. Pretty boring, but damn efficient. I first began using this technique after working with CSS-Guru Chris Coyier on the Digging into WordPress site. He writes everything in single-line format, so I gave it a shot – and liked it. There is a certain practical elegance to single-line CSS, and it involves much less scrolling, which is in itself a great way to optimize not just site performance, but your performance.
Bottom line: tabs and spaces consume bandwidth – design accordingly. A good way to go about it is to create two versions of your stylesheet: one for careful development and another optimized for production. More on this here.
Tip #11: Validate your CSS!
Once you get everything looking good, take a moment to run your stylesheet through an online CSS validator. It’s fast, free, informative, and is a great way to catch anything that you may have missed. I am always surprised to see some of the mistakes that I have made in my own stylesheets – some subtle, some blatantly obvious.
Bonus Tips: Other Ideas
A couple other ideas occurred to me while writing this post. First, one thing that most designers and CSS optimizers seem to miss is the blank space after selector names. For example, this:
a:link, a:visited {}
..could be written this way:
a:link,a:visited{}
Those extra spaces are useless to the browser, so feel free to remove them to save some a few more bytes.
The second thing that is pretty uncommon is removal of line breaks between rulesets. Consider the following code:
h1{color:#111}
h2{color:#333}
h3{color:#777}
About as optimized as is usually seen around the Web, but we can go even further by removing the line breaks after each ruleset:
h1{color:#111}h2{color:#333}h3{color:#777}
Almost ridiculous, this level of minification is probably best implemented after development. Otherwise you would be scrolling sideways along an seemingly endless string of code. If you can find (or configure) a minifier that will do this for you, it may further reduce file size.
It’s all about teh micro-optimization
Individually, each of these optimization tips may seem like small potatoes. But when you’re talking about 10, 20, or more instances of each optimization technique in a single stylesheet, it adds up in a hurry. Then multiply the savings of a single file by the total number of times it will be delivered. Doing the math, you’re going to see that these “micro-optimization” techniques are extremely beneficial in terms of download speed, bandwidth savings, and server resources. It may be difficult to just suddenly start writing well-optimized code, but by gradually integrating some of these techniques into your own practice, eventually you’ll be producing some high-octane, well-optimized CSS.
The bottom line is that you should be optimizing your production stylesheets. There are always cases where you want to leave the code formatted and human-readable, but for 99% of production sites, you are better off delivering the most bandwidth-friendly files possible. Machines don’t care how pretty your code is – just ask Google about that.
The easy way to do all of this
Writing clean and well-organized stylesheets often goes against most of everything we’ve discussed here. But it doesn’t have to. Eventually, I would like to get to the point where I can write well-organized and well-optimized CSS the first time around, without needing to edit or change anything later. Imagine just being able to write a production-ready stylesheet in Notepad. Bam! You’re done.
Unfortunately, all of those comments, whitespaces, and semicolons help us to produce stylesheets that are clean, organized, and manageable. And that’s perfectly fine. Adopt as many micro-optimization techniques as you want, and then continue to write your code with as much fluff as needed to make it understandable and maintainable. Then, once you have your development stylesheet ready to go, run it through a good CSS optimizer to optimize it for the production environment. Just keep your elaborately formatted stylesheet as-is, and then crank out an optimized production version to use on the “live” site. It’s like getting the best of both worlds!
Sure you can do all that work your self…..
Or you can just run your development file through a CSS compressor that does all this work for you so you can have the benefits of an optimized CSS file and still have a human readable and understandable CSS file.
For compressors I would recommend YUI compressor or the CSS Tidy
Shorthand optimized CSS,.. i use it too.. This article, is good advice.
I totally agree, but it has taken a while to get used to reading optimized CSS. Have you ever used CSScaffold? I still write optimized CSS, but CSScafold allows me to further compress code by enabling me to remove comments, all white space before out put. You can also use CSScaffold to prettify your CSS if you want. Regardless, I’ve found CSScaffold to be my silver bullet.
Hmm. Good article. Although I had to chuckle, because I do actually like to work with optimized, all in one line, no spaces code. HTML and CSS. I actually find it easier to read. I hate it when my CMS or my Editor or whoever came before me has left me with indented code. Especially if it has 14+ tables in it. Do you know how insanely ridiculous that gets on the eyeballs?
(Yes, the tables have to stay, they’re HTML e-mails.)
It’s also worth a mention that that any hexadecimal value for a colour can be abbreviated to 3 chars if they repeat themselves in their spectrum, so for example, red can be
#f00.You suggest we should use the CSS color ‘
red’ instead of ‘#cc0000’. But you should be aware that some browsers will interpret the text definition of a color different than the hex value. So my tip is always try to use the hex value for a color.For example see the gray/grey issue: http://weblogs.mozillazine.org/doron/archives/2007/10/the_world_is_greygray.html
Don’t forget that you can also write
background: red;asbackground: #c00;. If you have a hex code like#cc0000or#ffcc00they can be written as#c00and#fc0respectively.I’m totally with you on zeros and shorthand. Can’t tell you how annoyed I got at editing a client’s ‘pro’ template that was rife w/‘
0px’ ‘font-family: Arial’ for every declaration!However, I’m in the ‘keep the semi-colon’ camp. It keeps things from breaking and me from hair-pulling when I’m copying/pasting rules!
I also retain comments and indents, but remove line spacing in production files. But I don’t work on large enterprise sites, so it’s OK.
Mmmm how much does all of this really help though? I can write ‘
white’,#fffor#ffffffbut is#fff*really* making a significant difference? In the days of pretty ubiquitous broadband saving 500 bytes in a CSS file seems… precious.I write my CSS on one line. I then usually use Textmate’s formatting to break it out to one line per value since that’s easier to read. At some point, I might compress it back to a minified version in Textmate… but even if not, I’ve rarely seen the download of a single stylesheet take much time. The big wins are from not doing things like 5
@importdeclarations. I can just see people now, though - they’ll microoptimize their 8 modular CSS files.@Arnout: I agree about YUI compressor or the CSS Tidy - both excellent.
@9swords: Thanks for the feedback :)
@benjamin: I have seen CSScaffold but haven’t used it.. I will check it out. Thanks.
@Jaemi: I think you’re ahead of the curve. The more I work with CSS, the more I see how single-line, no-space code is the most efficient way to go.
@Alex: Good point. Thank you.
@Vincent: Good tip - Thanks.
@Adam: Definitely true. For the article, I grabbed
#cc0000on the fly, but didn’t notice its character symmetry. I was thinking something more along the lines of#D01212.@Catherine: Semi-colons on all declaration blocks are a must for me too. I remove comments and indents from production files and try to make changes only to the un-minified CSS file.
@rick: Even for a small site like this 500 bytes translates into around 40MB per month, and I usually remove around 10KB or so from my stylesheets. That’s a savings of around 750MB each month – nothing to sneeze at, especially if you’re paying for bandwidth.
Fair enough Jeff - I was considering this only from a load time perspective. However, where do most of the savings come from? It matters little to me if I write single line CSS or each value on a separate line if I go and choose Format CSS Compressed in Textmate and remove the whitespace before I deploy in any event. And, yes, 750m is noticeable… but when slicehost gives me 150g per month of transfer, it’s only significant if I’m close to that limit. 40m is a rounding error on that volume.
The reason I’ve always used some of these techniques is that they make the code more elegant as easier to read…. the optimization seems a minor side-benefit.
Jeff: I love your code block expansion trick. Is that a freely avaialble plugin or did you write it yourself?
There are some times when css optimization won’t work, especially when you’re relying on specificity to override inheritance. One must be careful when using shorthand properties like “background” and “font” because they tend to set properties in an all-or-nothing manner.
Usually you could set the overall background:
[selector] {background: #fff url('/path/to/image") top left fixed;}but when you need to alter a specific property for a specific instance, refer to the property directly:
[selector] {background-color: #c00;}This preserves the remaining properties. background: #c00; is not guaranteed to work as well.
A friend likes to code each selector on a single line like this:
[selector1] {background: ...; font: ...; color: ...; etc....}[selector2] {background: ...; font: ...; color: ...; etc....}[...]So he can scan through columns to find matched properties. I thought that was a pretty neat idea. (Emphasis on the tidy meaning of “neat”).
Another great way to deal with CSS is mixing single line with indentation.
For example: you can have a div container with a p inside with a link:
This is a text with a link
and style it like this:
.box {with:200px, height:200px; float:left}.box p {font-family:arial}.box p a{color:red;}This is really helpful. You can remove the extra space later.
Sorry, extra spaces were deleted from my previous comment. Refer to the following link in Pastebin to see the code example:
http://pastebin.com/KNtjwLSC
Thanks!
Great Article!!!
It is my understanding that with CSS3, three digit hex values are being depreciated. I can’t remember where I read that at the moment…does that sound familiar to anyone?
I hate looking at tabbed, multi-line CSS. Some consider it more readable, but I have to keep looking down for the next property it gets pretty annoying.
Single-line CSS as well as most of your micro-optimization techniques is definitely better that everyone should get used to. You can argue about later putting your CSS in a compressor, but I personally save way more time already writing optimized code so I can always change things later without it being a huge process.
My main stylesheet: http://cdn.myunv.com/css/uecore.css
some great ideas on how to cut donw the clutter; i’ll try to inlcude some of these in my next web projects. thanks again! c
nice run down. i write my css like that, no compressor needed. it just takes time to get used to.
one thing, regarding
background-color;i want to say that the marvelificient IE6 doesn’t recognizebackground:#fff, and you have to say-color;but i’m not remembering my source. and i’m not saying that you’re wrong. nice run down.I like using background-color when it comes to only applying a background color simply because it makes more sense in context to me.
It’s kinda like the old days of the bgcolor and background attributes.
ah. thx sunny, now i remember. it all depends on what you have going on in your styles and the cascade, but just declaring
background:#fffshould reset the rest of your background declarations, so if that is your aim, then its kewl. if not, i hold back on it.@Tony: Here is how to make the auto-expanding code box, by Chris Coyier at Digging into WordPress. Also, I am hearing a lot in this thread about using
background-colorinstead of justbackground, but I have never experienced any issues with it. Which browsers have issues?@Buda: Absolutely agree - I use that technique mixed in with my other fold-coding formatting techniques. It’s perfect for certain selectors and sub-selectors.
@Benjamin: Interesting, I haven’t heard anything about it until now. It sounds like a bad idea to me, but who am I to argue with the W3C? Honestly I doubt they would do something like that..
@Sunny: Makes complete sense, and sounds like you have your CSS well under control! Learning how to write clean, optimized code without relying on an automated minifier takes practice, but is worth the effort.
@chris: My pleasure - thanks for the feedback :)
@albert: I haven’t experienced that, or perhaps I have forgotten since I pretty much stopped supporting IE6. If you have a reference, that would help sort it out. Thanks!
Good tips. I’ve been using most of these techniques for a while during the development phase, no need to compress the CSS before deploying unless you really need to optimize download speed (mobile, high traffic).
I usually run YSlow and Page Speed and check what it says…
I’ve written a couple days ago about how I structure my CSS files, I think you may be interested.
PS: YSlow has a built-in CSS and JS minifier.
Cheers!
Finally, I’m not the only crazy one who loves this sort of CSS code writing!
Great article as always, especially for newbies who can easily get overwhelmed with 10 CSS statements, because they are taught to write CSS using indentation, spacing, returns and so on!
Some valid points: http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize.
Isn’t the font short-hand called simply “font”? You used “font-family” there too.
(Great tips, anyway!)
There’s an error in your example for optimization #2.
“In this order, the latter rules will be applied and the first ignored.”
This statement is incorrect, since it does not account for specificity.
#wrap phas a higher specificity than justp, so no matter what order they’re in — the former will always “win”.Nice article!
Like you point in the #3 topic, I “discovered” a better way to reduce even more of some properties for border, padding, margin (and so on) parameters.
Take a look: Imagine you have a text field with colored border, like this:
input[type=text] { border-top:1px solid #ccc; border-right:1px solid #fff; border-bottom:1px solid #fff; border-left:1px solid #ccc; }With a hand of “micro-optimize” I got this result:
input[type=text] { border:1px solid; border-color:#ccc #fff #fff #ccc; }Cool uh?
Thanks again for share! I hope this example I wrote could help anyone also…
I’m usually don’t spam, but a lot of these optimizations can be achieved by a PHP class I wrote some time ago:
http://www.phpclasses.org/package/5950-PHP-Compact-several-CSS-files-into-a-single-file.html
This class however, won’t convert margin-top:1px;margin-bottom:1px;margin-left:1px;margin-right:1px into margin:1px;
For that, you should use YUI Compressor or another one, this class however, does everything on the fly (and uses cache for better performance).
However, a lot of optimization can also be done on javascript files, for that, you can download a class that does both (This one isn’t mine xD):
http://code.google.com/p/minify/
Greetings !
@Edson:
padding, margin, border, and other such as border-radius etc can be micro-optimized:
margin-top:50px;margin-bottom:50px;margin-right:50px;margin-left:50px;can be converted into:
margin:50px;margin-top:50px;margin-bottom:50px;margin-left:100px;margin-right:100px;can be converted into:
margin:50px 100px;margin-top:50px;margin-bottom:175px;margin-left:100px;margin-right:100px;can be converted into:
margin:50px 100px 175px;Finally:
margin-top:10px;margin-bottom:20px;margin-left:30px;margin-right:40px;Converted:
margin:10px 40px 20px 30px;Also, font, background and others can be converted into much smaller code, take a further look here:
http://www.threestyles.com/tutorials/css-shorthand-guide/
Greetings !!
Hmm. So nice to minify code by hand.
Just use shorthand where appropriate, the rest is kind of dumb. Don’t write unreadable single lines just to make the code shorter.
Background: #FFF for setting just the background color is not nice, it will implicitly set all of the defaults for the other properties, slowing down your css rendering. It will also take precende and force you to use !important if you want to change background-color later.
@unreal4u yeah! I know!
I just minimize even more the minified version, you noticed that?
:)
I too am a fan of the indented single-line CSS style.
One thing to note, with the still remnant ie6 users be aware that ie6 runs into problems parsing CSS when the whitespace is removed between the semicolon at the end of a method and the beginning of the next.
e.g. p{margin:0;padding:0;}
I don’t know about you, but I usually use a computer to do things for me that I don’t want to do…
for instance, I enjoy writing readable, spaced out CSS in multiple files and letting a computer parse, minify and aggregate it
not only would this save me countless hours of byte-pinching, but it actually results in a workable system in regards to versioning
if all your css is in 1 file and on 1 line, every change is going to be a change to the entire set
this would make versioning almost completely useless and can’t possibly increase readability or maintainability…
I do see a use in most these things though, which is why most of them are already adopted by the minifiers out there, except the semicolon thing, coz I think that bugs out in some cases
btw, for some1 so keen on optimization, u should rly consider using sprites :P
These are fantastic tips, but almost all of them can be done in an automated fashion, using a CSS minifier. You shouldn’t be obfuscating your development code manually, because it makes your code harder to maintain. Ultimately, the harder your code is to maintain, the more work it becomes for you.
I also have to point out something critically important that MANY designers fail to take into account because they don’t really approach things like this from a development mindset: when you put all your CSS properties into a single line, you effectively lose the ability to do a quality diff or blame on edits to this file under version control. This makes it significantly harder to see what has changed from one revision of a file to the next.
Not only that, but while properties-all-on-one-line results in less vertical scrolling, it definitely results in more horizontal scrolling. Now, since any source code file, CSS or not, is practically guaranteed to scroll vertically, why not try to eliminate the horizontal scrolling?
I’ve been doing this for a long time, and for me, ease of maintenance pretty much (but not always) wins over “coolness.”
I think it all comes down to what works best for whom. What’s the project, how much code is their likely to be, etc. For small website I do on my own, which would likely be started all over if I ever gave them up, I code the way I want to; the one-line coding is easier for me.
On sites where there are multiple people maintaining the code, considerations might be different. But, in my case, we use a CMS, and I generally copy the code for the page I’m working on out, into my Editor of choice, and then putting it back in when done. The CMS will indent as it likes, but while I’m working with it, I can remove all the indentation. Like I said, once you have 14 tables in an email newsletter, I find helpful comments a lot more useful than indentation.
I completely agree with seutje. If you are the only one that will ever see the code, then your own system may work. However, beyond your own personal site, you could never be sure of that. So you need to create files that won’t leave your client high and dry when they need to upgrade their site. This is also true when working with a team.
@jason your example works fine in IE6. the only example that i’m aware of with spacing is in the shorthand for background; the positions need space or they won’t work. pretty sure that holds for IE7 too.
@cowboy huge fan. but i’m going to continue disagreeing; we rocked these min styles at my last gig and i most certainly used blame to find out what went awry. it’s totally relative, but if you have dedicated frontend, they should be able to hang.
with that said and in all fairness, i completely agree with
@jaemi it all comes down to what works best for whom
Jeff I have a quick question. Say you have a top padding of 20px and no other padding. Would you code it “
padding-top:20px” or “padding:20px 0 0 0”?I do all of what you’re saying, plus, as @Laz suggested, using “
font:” instead of “font-family:” in (for example) tip #7.(I also avoid color names. I found, somewhere, a chart of the “official” 128 color names and equivalent hex codes. I even wrote myself a web page with a table of the hex codes and the color names for cross-browser comparison. Hah!)
For further optimization, I do two things. First, I prepare for my own sanity by sorting properties alphabetically within each selector (for easy location later). Then, I may combine related selectors on one text line: all the headers (
h1,h2,h3…). Easy to scroll left and right with my editor for maintenance, and saves just a little more bandwidth.Super smart article to do file size reduction in css file
Recommended to all (Novice to Pro)
Like it
@Laz: Very true. Article updated with the correct information. Thank you!
@Mathias Bynens: Good catch - article updated with correct info. Thanks :)
@Edson: Awesome technique - Thanks for sharing :)
@Jason: Interesting.. is there documentation anywhere for it?
@seutje: Relax, partner - I use plenty of sprites! Look harder :)
@Jaemi: Completely agree - it all depends on project specifics and other needs. There are many excellent strategies for writing/delivering well-optimized CSS.
@Shay Howe: Great question. In general, fewest characters wins. But if you are styling an element that already has padding set from some other selector,
padding:20px 0 0 0will change the existing values, whereaspadding-top:20pxwill not.Thanks to everyone for leaving feedback on this post!
how about editting margin-bottom, margin-top, margin-left, margin-right in one piece of code such as
margin:10px 20px 30px 40pxgood points.. use most of them except base64.. will try it soon
Personally I find formatting my CSS by rule-per-line much easier to read than expanded and indented attribute per line rules, but that’s just me.
What @Ben says about version control is very true. Also personally, I think leaving out comments, although a valid method of optimisation, make later edits a living nightmare, especially if it’s not your code. Also in some applications you might actually need CSS comments, Wordpress themes come to mind.
That being said, each of these things only have their benefits in either the live online environment, or the development environment. Minified optimised code has no benefit in the development environment, and nicely formatted well documented code has no benefit on the live environment.
So for sites where every last character matters, why not implement an “upload procedure” where you can keep your code however you like in your development environment, then strip, compress and minify ad nauseum directly before upload?
Hokya, shorthand property declaration order goes clockwise from top. So your declaration would represent:
margin-top: 10px;margin-right: 20px;margin-bottom: 30px;margin-left: 40px;Just thought I’d correct for future visitors.
That’s cool, I hope i have this time to write like you
Like some of you allready commented about semicolon; it’s a must for my CSS too, and not only because it bugs my eyes if I don’t see it, but because it makes the code easy for copy/paste and also helps to prevent errors when you add styles for elements, even when using syntax highlighting.
Great article, BUT it does not make sense to strip out white space and place all selectors on one line, when you can compress the file instead.
The goal should be optimised/readable code.
This article is awesome
I just started using Less CSS (http://lesscss.org) to get more readable CSS with free minified output on the fly.
Hi, thanks for your article.
I currently use and like almost all of the techniques listed. However, I do not omit the last semi-colon. The reason: If/when something new is added, and I forget to add the semi-colon BEFORE adding the new styles…. == Oops!
But, the other ideas are very helpful.
Thanks!
- Rod
I know the semicolon is challenging but hear me out:
>> semicolon is used to *separate* properties.
so prove that you are a designer that can change his/her mindset !
let’s dump the last semicolon for good ;)
Ah, Laurent. That is a very good point. Well taken. Thanks, I may just dump the last semi-colon now! Look at me! I am a changed Man!
Problem with dumping the final semicolon is that in related technologies like PHP the semicolon is required. The fact that Wordpress templates use inline PHP snippets that skip the semicolon is irrelevant.
So, removing final semicolons from CSS files just to save 8 bits per declaration doesn’t really save time when they are applied through habit.
Some jokers fix this problem by prefacing all statements with a semicolon “just in case” they need to cut and paste between declarations and files. Personally, I find this workaround ludicrous.
Is it good to write color name instead of color code?
“ ..writing “red” is more efficient than “
#cc0000”…”I read once (if I remember correctly) that color name can be different in different browser! or it is good to use color code.
but i don’t think that color code will work on all kind of browser
>>
a:link, a:visited {}>>..could be written this way:
>>
a:link,a:visited{}yes. and we can catch many funny bugs with ie6 for example.
I find my approach insanely easier.
You can get YUI Compressor in 1 line of bash…
wget -q http://yuilibrary.com/downloads/yuicompressor/yuicompressor-2.4.2.zip && \
unzip -q yuicompressor-2.4.2.zip && \
cp yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar . && \
chmod u+x yuicompressor-2.4.2.jar && \
rm -rf yuicompressor-2.4.2.zip yuicompressor-2.4.2/ && \
( which java >/dev/null 2>&1 || echo “You need to install Java…” >&2 )
Then you can minify all your CSS files with the touch of a button (ok, well, the run of a bash script):
#!/bin/bash
FILES=$(find ${1:-’.'} -type f -iname *.css);
for FILE in $FILES; do
./yuicompressor-2.4.2.jar -type css $FILE -o ${FILE%.css}.min.css;
done;
which automatically makes a .min.css for every .css file it finds after minifying it with almost (if not all) the same micro-optimizations you have specified.
Why would you ever do this by hand…?
Because I enjoy the fine art of writing and optimizing CSS. It’s a beautiful language that is a joy to write and format.
Sure you could just stick a needle in and be done, but if you’re writing clean code to begin with, there’s no need for fiddling with YUI, bash, or anything else.
I wouldn’t really consider writing minified CSS “beautified code”, but to each their own.
An automated way allows you to write the most beautiful and verbose CSS you’d like with no penalty and automagic minification, :).
Yes automation is a good thing!
I’m pretty sure I mention that point in the article, but it’s always good to hear people agree :)
Nice advice Jeff! I love the way you explaining it in ease but detailed.
I would like to add more, use more classes to join styling. thanks!
I agree with everything in this article with the exception of eliminating unnecessary white-space (line-breaks, tabs, spaces) and/or code folding during the development process. In my opinion, readability is more beneficial, especially in a team environment. Clean, tabbed CSS allows for others to more easily interpret the code and can aid in certain optimizations discussed in this article like eliminating duplicate properties. I fully support using every shorthand technique available, but personally prefer to defer the white-space optimizations until the build process when I minify/concatenate the stylesheets. Just my 2 cents, but all-in-all a great article.
Shorthands are good in minimizing but one must mention that they set all omitted values to default ones. So if you write:
body { background: url(…) }and then after
body { background: #FFF }you will see no picture because it was set to default value ‘
none’. Sometimes it can produce bugs in more complicated cases. So use with care.Similar you don’t need to write ‘
normal’ in font. Not just because there are several values can be set to normal but because they do so without it also.p { font: 1.33em/1.33 Georgia, serif }will do same work as well.But you can’t shorten
font-familyto font because there also must be font-size. (Except you refer to system font such as caption, icon, menu, etc. according to CSS 2.1).I definitely agree on #10 (writing everything in a single-line format). It makes me so much more efficient when I’m writing my style sheets. However, I must disagree on #7, but that’s due to my personal preferences. I like to keep that last semicolon just for the sake of consistency and for avoiding any errors when updating my code with new properties.
Btw, great article :)
I write my code on single lines (per selector) and when I’m finished I do the 100% micro with TopStyle. But still I don’t put everything on single line - just remove spaces, order properties in ascending order (eg
height:105px;position:relativeAND NOTposition:relative;height:105px;)Next time I open my css, it’s neat’n clean for next editing.
I think that is the most important thing: Having a system that works for you, and is easy to maintain. Sure, there are tools out there to squeeze out every last byte of un-needed code. But, in the end, you have to be comfortable with how it ends up, and how to maintain the code in the long-run. Cheers. This has been an interesting conversation.
Thanks for this article & discussion full of passion for lean, clean, CSS & code. Your focus (footer) is clear to me. Respect.
Thanks for the post Jeff! I love the way you explaining it in ease but detailed.
Thanks once again
My version of CSS Optimizer with tips and techniques.
http://www.lukicmilos.in.rs/CSSOptimizer/
Hope you like it. :D