15 Ways to Optimize CSS and Reduce CSS File Size

15 Ways to Optimize CSS and Reduce CSS File Size


15 Ways to Optimize CSS and Reduce CSS File Size

Introduction

I have gathered a long list of CSS optimization and file size reduction techniques that have been using by most designers/developers. Depend on the complexity of your CSS code, these techniques might greatly reduce your CSS file size, or maybe just a few kilobytes.

Also, you might also want to read my previous post regarding CSS - 15 CSS Tips and Tricks to learn how to write more efficient CSS code.

1. Use CSS Sprite

"CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment." - Yahoo Developer Rule

This method is proven to greatly reduce the amount of HTTP request and very effective for high traffic websites. The famous community news website Digg is using this method.

More details about CSS Sprite:

2. Combined all CSS files into single file

"When a user is opening your website every object on the page (e.g. images or scripts) will require a round trip to the server. Those HTTP requests will delay the response time of your site, and if you are loading dozens of objects this delay can add up to several seconds." - Dailyblogtips

This technique is quite similar to CSS Sprite, at least they have the same purpose - to reduce HTTP requests. So, if you have 3 CSS files in your webpage, browser will send 3 HTTP requests to the server. Simple mathematic, 1 CSS file = 1 HTTP request. I have seen some of the websites that have 6-7 CSS files in the header, and that will affect your website loading time for sure.

Before

<link rel="stylesheet" type="text/css" href="content.css" />
<link rel="stylesheet" type="text/css" href="about.css" />
<link rel="stylesheet" type="text/css" href="contact.css" />

<link rel="stylesheet" type="text/css" href="layout.css" />

<html>
	<head>
		<title>CSS</title>
		<style>
		body {
			font-family:verdana;
			margin:0;
			padding:0;
		}
		
		h1 {
			font-weight:700;	
			margin:5px 0;
		}
		
		......
		......
		......
		
		</style>
	</head>
</html>

<html>
	<head>
		<title>CSS</title>
		<link rel="stylesheet" type="text/css" href="style.css"/>
	</head>
</html>

After

<link rel="stylesheet" type="text/css" href="content.css" />
<link rel="stylesheet" type="text/css" href="about.css" />
<link rel="stylesheet" type="text/css" href="contact.css" />

<link rel="stylesheet" type="text/css" href="layout.css" />

<html>
	<head>
		<title>CSS</title>
		<style>
		body {
			font-family:verdana;
			margin:0;
			padding:0;
		}
		
		h1 {
			font-weight:700;	
			margin:5px 0;
		}
		
		......
		......
		......
		
		</style>
	</head>
</html>

<html>
	<head>
		<title>CSS</title>
		<link rel="stylesheet" type="text/css" href="style.css"/>
	</head>
</html>

3. Make CSS as an external file

"Using external files in the real world generally produces faster pages because the CSS files are cached by the browser. CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests." - Yahoo

This is so true. There are a lot of websites still using inline CSS. From develoment point of view, although there are a lot of tools out there to help out, but, we should always try our best to separate different languages into different files. For example, try not to put inline CSS, javascript in the HTML documents, but put them into external files. It makes your code easy to maintain and read. Besides that, it also increases and optimize website performance.

4. Always put CSS file in the header/top

"While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. " - Yahoo

Putting stylesheet in HEAD can avoid two problems: the blank white screen and flash of unstyled content. Steve Souders did some tests on what will happen if you put the Stylesheet in somewhere else in the webpage.

Before

<link rel="stylesheet" type="text/css" href="content.css" />
<link rel="stylesheet" type="text/css" href="about.css" />
<link rel="stylesheet" type="text/css" href="contact.css" />

<link rel="stylesheet" type="text/css" href="layout.css" />

<html>
	<head>
		<title>CSS</title>
		<style>
		body {
			font-family:verdana;
			margin:0;
			padding:0;
		}
		
		h1 {
			font-weight:700;	
			margin:5px 0;
		}
		
		......
		......
		......
		
		</style>
	</head>
</html>

<html>
	<head>
		<title>CSS</title>
		<link rel="stylesheet" type="text/css" href="style.css"/>
	</head>
</html>

After

<link rel="stylesheet" type="text/css" href="content.css" />
<link rel="stylesheet" type="text/css" href="about.css" />
<link rel="stylesheet" type="text/css" href="contact.css" />

<link rel="stylesheet" type="text/css" href="layout.css" />

<html>
	<head>
		<title>CSS</title>
		<style>
		body {
			font-family:verdana;
			margin:0;
			padding:0;
		}
		
		h1 {
			font-weight:700;	
			margin:5px 0;
		}
		
		......
		......
		......
		
		</style>
	</head>
</html>

<html>
	<head>
		<title>CSS</title>
		<link rel="stylesheet" type="text/css" href="style.css"/>
	</head>
</html>

5. Use Link instead of @import

A details testing and analysis from indicates using @import can affect the performance of your website. The result of the analysis:

  • Using @import within a stylesheet adds one more roundtrip to the overall download time of the page.
  • Using @import in IE causes the download order to be altered. This may cause stylesheets to take longer to download, which hinders progress rendering making the page feel slower.

6. Use CSS Shorthands

By grouping all the same properties settings together, CSS shorthand definitely able to help you reduce and optimize CSS files. Instead of multi lines of properties, we'll able make it a one liner. The following is all the CSS shorthands:

CSS Shorthand

/* MARGIN */
h1 {margin:1em 0 2em 0.5em;}

h1 {margin-top:1em;
   	margin-right:0;
   	margin-bottom:2em;
   	margin-left:0.5em;
}

/* BORDER */
h1 {border:1px solid #000;}

h1 {border-width:1px;
    border-style:solid;
    border-color:#000;
}

/* BORDER WIDTH */
h1 {border-width:1px 2px 3px 4px;}

h1 {border-top-width:1px;
	border-right-width:2px;
	border-bottom-width:3px;
	border-left-width:4px;
}

/* BACKGROUND */
div	{background:#f00 url(background.gif) no-repeat fixed 0 0;}

div	{background-color:#f00;
	 background-image:url(background.gif);
	 background-repeat:no-repeat;
	 background-attachment:fixed;
	 background-position:0 0;
}

/* FONT */
h1 {font:italic small-caps bold 1em/140% "Lucida Grande",sans-serif;}

h1 {font-style:italic;
	font-variant:small-caps;
	font-weight:bold;
	font-size:1em;
	line-height:140%;
	font-family:"Lucida Grande",sans-serif;
}

/* LIST STYLE */
ul {list-style:square inside url(image.gif);}

ul {list-style-type:square;
	list-style-position:inside;
	list-style-image:url(image.gif);
}

/* OUTLINE */
h1 {outline:#f00 solid 2px;}

h1 {outline-color:#f00;
	outline-style:solid;
	outline-width:2px;
}

7. Group Similar Styles

This happens easily after a long development. We just declare the same styles over and over again without realising that something exactly the same is already exist. It's good to look back the CSS code and reanalyse it, so that similar styles can be grouped together.

Before

h1 {padding:5px 0; font-family:verdana; font-weight:700;}
#box1 .heading  {padding:5px 0; font-family:verdana; font-weight:700;}
#box2 .heading  {padding:5px 0; font-family:verdana; font-weight:700;}

After

h1, #box1 .heading, #box2 .heading  {padding:5px 0; font-family:verdana; font-weight:700;}

However, for most cases, the CSS Styles not neccesarily appear eaxctly the same, like this:

Before

#nav a.home {padding:5px 0; font-family:verdana; font-weight:700; background:#fff url(home.gif) no-repeat 5px 5px}
#nav a.portfolio {padding:5px 0; font-family:verdana; font-weight:700; background:#fff url(portfolio.gif) no-repeat 5px 5px}
#nav a.contact {padding:5px 0; font-family:verdana; font-weight:700; background:#fff url(contact.gif) no-repeat 5px 5px}
#nav a.about {padding:5px 0; font-family:verdana; font-weight:700; background:#fff url(about.gif) no-repeat 5px 5px}

After

#nav a {padding:5px 0; font-family:verdana; font-weight:700; background:#fff no-repeat 5px 5px}

#nav a.home {background:url(home.gif)}
#nav a.portfolio {background:url(portfolio.gif)}
#nav a.contact {background:url(contact.gif)}
#nav a.about {background:url(about.gif)}

We all can see the differences for this example, it's a great method to reduce CSS files size and increase readability.

TO THE EXTREME: CSS File Size Reduction

This section is dedicated for those who want to further reduce CSS file size. Some of the tips and tricks can only reduce few bytes from the file, but it's will be good to know all the possibilites anyway. :)

8. Reduce The Number of Line Breaks

h2 {
	font-family:verdana;
	padding:0;
	margin:5px 0;
	color:#333;
	text-decoration:underline;	
}

/* you can do it like this */
h2 {font-family:verdana;padding:0;margin:5px 0;color:#333;text-decoration:underline;}

9. Remove the last semicolon

h2 {font-family:verdana;color:#333;}

/* removed */
h2 {font-family:verdana;color:#333}

10. Use simple comments

/************************************/
/*          Content Page            */
/************************************/

vs

/* content page */

11. Simple Color

Instead of using full color code like this:

#FFFFFF, #113344, #AABBCC, #FF0000

We can do it like this

#FFF, #134, #ABC, #F00

However, we won't able to change anything like this:

#C4C4C4, #1A2B3C

12. Remove "px"

h2 {padding:0px; margin:0px;}

/* removed */

h2 {padding:0; margin:0}

13. Using shorthand

As mentioned above, it really helps in reducing file size.

14. Remove unused classes

During the development, due to the design changes, some of the classes that we have created might not in use. Sometimes, we just have to skim through the CSS code, and identify them and clean up the code.

Dust-Me Selector is a Firefox extension that finds unused CSS selectors. 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. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered.

15. Use CSS Compression Tools

Or, if you don't want to do all that manually, you can always use the following tools:

CSS Optimizer
Flumpcakes CSS Optimizer
Clean CSS
CSS Drive CSS Compressor
Online YUI Compressor
Style Neat

Reference/Credit/Further reading

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

30 comments

dlv
Mon, 24th August 2009
really nice article ! i'm agree with all you explain

Also, i want to share the utility "Online YUI Compressor" which compress CSS and JavaScripts files online using the great YUI Compressor 2.4.2 by Yahoo.
(http://www.refresh-sf.com/yui/)

Another interesting online utility is "Styleneat", which organize our CSS, sorting selectors and properties... (http://www.refresh-sf.com/yui/) )

thanks for share this article
adeux! Reply
Eric
Mon, 24th August 2009
Hey Kevin, great info!
But in part 1, CSS SPRITES your second link should be the following:

http://azamsharp.com/Posts/216_Combining_Images_CSS_Sprites_to_Increase_Performance.aspx Reply
Eric
Mon, 24th August 2009
BTW, @Demian YOUR SITE LOOOOOKS SWEET!!!!!!!!!!!!!!!!!!!!!
I love your play on the lavalampish navigation and your mouseover of your logo...gorgeous touch!
I sent you a message from your site, PLEASE PLEASE PLEASE CONTACT ME! Reply
Volkan
Tue, 25th August 2009
Good one, thx :) Reply
siva
Wed, 26th August 2009
Many thanks Reply
ดูหนังอฟรี
Mon, 7th September 2009
Good article. Reply
LuciferX
Thu, 10th September 2009
Really very nice article
Thank's I learned 2-3 things ^^ Reply
Amish
Fri, 11th September 2009
Very nice list; several new ones for me to incorporate.
Thanks.
Small typo in #9: last letter should be an "n" in the title. Reply
kevin Admin
Sun, 13th September 2009
:) thanks. updated the article. Reply
LiteTheme
Tue, 15th September 2009
The extreme.. LOL! LOVE IT! ;) Reply
tours in singapore
Thu, 17th September 2009
very good resource...thanks mate...really learnt alot from this post...thanks again Reply
bucabay
Wed, 7th October 2009
Do not sacrifice the clarity of your CSS for optimization. The same rule that applies to separating your content from design, or program logic from presentation applies to your code and optimization, whether it be server side code, HTML or CSS.

Worrying about optimization prematurely is just going to hinder your development/design.

There are server side tools such as Gzip, and automated minification tools that you can run your CSS though. Worrying about a single semicolon, newlines, the type of comments, or CSS shorthand is only going to hinder the clarity of your code.

Even multiple files issues should be taken into consideration only if it becomes a problem for your visitors. Modern browsers will use a single TCP connection for multiple files from the same domain, making the issue minimal.

If you follow a good design practice, you\'ll notice that you are also optimizing your code, as well as making it easy to optimize if further automatically. Reply
Ryan Roberts
Wed, 28th October 2009
Here\'s another extreme one for you...

Use 700 instead of bold, and 400 instead of normal. For example;

font-weight: 700;
font-weight: 400;

:) Reply
Ryan Roberts
Wed, 28th October 2009
In fact I noticed you\'re already doing that in the CSS you just don\'t mention it as an example. Reply
pdf search
Wed, 5th May 2010
I learned a few things your way... Reply
Artur
Mon, 24th May 2010
very good resource
www.optimizecss.com Reply
SaqibDesigns
Wed, 22nd September 2010
Thanks for the nice tut mate... really nice techniques.. I learned few things but in after I am also agreed with "bucabay" 's comment..

well thnx again.. :) Reply
Dennis
Tue, 21st December 2010
Great article. Another thing I've been playing with to help reduce overhead is to make my server dish .css as .php and force the header, This way I test to see what Browser the user is using and serve the relevant style sheet for their Browser or Device they're using. This way I can also place any particular css properties targeted at specific browsers, and not have css properties that Browser doesn't use or Understand, esp. with the css3 components. Reply
Alexandru Objelean
Tue, 5th July 2011
One of the existing tools which can help you to apply these best practices is: wro4j (web resource optimizer for java): http://code.google.com/p/wro4j/wiki/Features
Reply
Endy
Tue, 2nd August 2011
very interesting article ...
very complete discussion of what you write ...
thanks for sharing.... Reply
Jatin Soni
Mon, 22nd August 2011
Is it really good to remove last semicolon from the class? Reply
raj jaswal
Mon, 6th February 2012
.really learnt alot from this post Reply
chelladurai
Tue, 7th February 2012
Really useful article... Reply
syed shaik sha vali
Thu, 2nd August 2012
Great article. Reply
vishal
Tue, 18th December 2012
thanks gud job Reply
alisheytoon
Wed, 22nd May 2013
Thanks For all help Reply
Indra
Fri, 12th July 2013
Good article on reducing CSS file size. BTW there are some typos in this sentence under no. 7. Group Similar Styles: "However, for most cases, the CSS Styles not neccesarily appear eaxctly the same, like this:" Reply
chiranjivi
Mon, 2nd September 2013
thanks dude like your tips and helps me a lot... Reply
Bilbo Baggins
Sun, 15th December 2013
There is no reason to do #8 through #13. If you are using a good minifier, it will do all of those for you. Reply
Balasubramani
Sun, 6th July 2014
This topic is very use full....... Thanks Buddyyyyyyyyyyyy Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement