5 Step Style Sheet Weight Loss Program
Tags: Beginner
Does your style sheet ever feel bloated and overweight? If you notice some love handles growing on your style sheets, it may be time to stop and give it a good make over. Learn the following steps and your style sheet will be in shape in no time.
Step #1 – Learn How to Group Selectors
What is a Selector?
For those who are not familiar with the term “selector” you can refer to this quick overview of CSS syntax by w3schools.com.
Un-Optimized CSS Code
In this example, you will see the same properties within 3 different selectors.

Optimized CSS Code
You can optimize the above css by grouping selectors that have the same properties. Each selector should be separated with a comma, see below for an example:
h2, p, .block {
font-size: 1.5em;
padding: 10px 10px 10px 25px;
margin: 10px 0;
border: 1px solid #ddd;
background: #f0f0f0 url(crown.gif) no-repeat 5px 10px;
}
Step #2 – Learn Specificity
What is CSS Specificity?
Selector specificity is a process used to determine which rules take precedence in CSS when several rules could be applied to the same element in markup. – Juicy Studio – Selector Specificity
Un-Optimized CSS Code
It’s important to understand the different levels of importance in the specificity rules. Writing the same level of css rules will lead to style conflicts and code redundancy.

Optimized CSS Code
When you fully understand CSS Specificity, you can reduce code by combining its common properties and specifying its importance for the unique values. You will soon find clever ways to start optimizing your code, mixing and matching as you move along. Here is a simple example of how to optimize the code above using CSS Specificity.
h2 {
font-size: 1.5em;
padding: 10px 10px 10px 25px;
margin: 10px 0;
border: 1px solid #ddd;
background: #f0f0f0 no-repeat 5px 10px;
}
h2.best {background-image: url(crown.gif);}
h2.fav {background-image: url(heart.gif);}
h2.comments {background-image: url(balloon.gif);}
h2.twitter {background-image: url(balloon_twitter.gif);}
#featured h2.twitter {
background-color: #fffdd7;
border: 1px solid #ddd991;
}
Related Articles
- HTML Dog – Specificity
- Smashing Magazine – Things You Should Know
- CSS Tricks – Specifics on CSS Specificity
- Jonathan Snook – Understanding CSS Specificity
Step #3 – Learn How to Combine Classes & IDs
On a related note, you can also optimize your CSS and HTML markup by mix and matching Classes and IDs. Keep in mind that by adding multiple classes on one element, you are able to combine various properties together to get the results you are looking for. Assigning IDs in the right places also allows more control over your styles.
HTML
<div id="featured"> <h2 class="best double">Best of</h2> <h2 class="fav double">Popular Posts</h2> </div> <div id="disable"> <h2 class="comments double">Comments</h2> <h2 class="twitter double">Twitter</h2> </div>
CSS
...
h2.best {background-image: url(crown.gif);}
h2.fav {background-image: url(heart.gif);}
h2.comments {background-image: url(balloon.gif);}
h2.twitter {background-image: url(balloon_twitter.gif);}
h2.tools {background-image: url(wrench_screwdriver.gif);}
h2.double {
width: 263px;
float: left;
margin: 0;
}
#featured h2.double {
background-color: #ffe2e2;
}
#disable h2 {
filter:alpha(opacity=40);
opacity:.40;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";
background-color: #d5d5d5;
}
Step #4 – Learn CSS Shorthand
Shorthands allow you to specify the values of several properties with a single property. Since this topic has been covered many times by various blogs, please check out the links below for examples.
Related Articles
- Sitepoint – Introduction to CSS Shorthand
- 456 Berea St – Efficient CSS with Shorthand Properties
- Leigeber – CSS Short Hand Cheat Sheet
Step #5 – Break Apart Your Style Sheet – @import
When working on a large site, the style sheet is going to be packed with full instructions for the site layout and presentation. To get organized and to break apart your massive style sheet into modules, you can use the @import technique to import your various styles.
HTML
Just like you would normally call your style sheet…
<link rel="stylesheet" type="text/css" href="styles.css" />
CSS – styles.css
Your initial styles.css file will act as your master style sheet and will call your other style sheets. (*I nested the other styles in the ‘styles’ folder for organizational purposes. This is a personal preference, you make the choice.)
@import "styles/main.css"; @import "styles/checkout.css"; @import "styles/shoppingcart.css";
Related Article
Related Posts
Author Bio
My name is Soh Tanaka and I am a Los Angeles based designer/front-end developer specializing in CSS driven web design with an emphasis on usability and search engine optimization. I also run a CSS Gallery which is updated daily with the best CSS websites from around the world. Come check it out!
You can learn more about me or
Follow me on twitter for more updates and resources!
Did You Enjoy This Post?
Subscribe via RSS or by email to get all upcoming tutorials and articles delivered straight to you.




+ Add Comment52 Peeps Have Spoken Their Minds...
Good article but I disagree on the @import section: the more css files you have, the more http requests are needed. It affects the performance of the website.
Nice tips man!
thx :-P
AWESOME analogy! Very well written article, and some great tips. One of the things that makes me most disgusted when reworking some one’s code is really bloated CSS file. I like breaking up my css into multiple files, but get concerned that I might be over doing. I try to use different styles for “sections” of a site that are vastly different than the majority of the site (i.e. a user page, or checkout), any other suggestions on how to break your css into multiple files?
Great examples really do help you understand how this all works. Thanks!
Danny, good point!
Although I’ve had experience working on a large scale e-Commerce site, and when the style sheet reaches about 50-100k, in my opinion it really should be attended to by breaking apart into reasonable sections. It may not reduce the http requests, but it does make the style sheet a lot easier to work with.
Example:
- Checkout/Shopping Cart deserved to be its own file
- Certain PPC landing pages that were unique to the site were grouped into one style sheet
- Since the site was replicated to create other similar e-Commerce sites, the skin/theme was broken out into its own file.
I do agree though that getting too specific with the style sheet can be annoying as well.Typically if a site is not that large, I just stick to one main style sheet and call it a day :-) No need to break out the type, colors, etc in my opinion.
Great tips :). Thank you for collecting this techniques.
I guess that “Step 5″ will not work fine in IE6, al least not for me, because Internet Explorer 6 and below do not support the media designation using @import.
You can also start coding your CSS on one line instead of the formats shown above. I started that about 1 year ago and while it took a bit of getting used to it does trim some weight. Also although you used CSS shorthand for the padding in the examples I notice you didn’t call it out. That is one thing I know I see beginners not doing that would save a bunch of time later and saves some weight on your code.
Now that I have spouted off I can’t remember how long ago I coded the site linked to in my sig so I wonder if I did what I just mentioned. Ah well. Thanks for the tips.
Hey Gregorio!
To my understanding the following syntax WILL be buggy for Internet Explorer:
@import “main.css” screen;
or
@import “main.css” screen, projection;
BUT If you leave the media types off you will be good to go:
@import “main.css”;
If anyone can drop some science on this, it would be greatly appreciated!
———
Hey Curtis!
That is true that coding per line will cut some weight, but one pet peeve of mine that I can’t get over is when going back into the style sheet to see the dense lines of code… Especially when working in a large team of designers/developers, I feel clean, organized, and easy to scan CSS is the way to go, and I hate having to squint to see which properties I need to change.
You do have a very valid point though so don’t mind my excuses haha maybe just not my cup of tea :-p
Thanks Curtis!
As far as I know there is no proper way of using media types cross browser inside of your style sheets so the only other cross browser compatible way is to use something like this.
<link rel="stylesheet" type="text/css" href="styles/main.css" media="screen" charset="utf-8" />
Or
<style type="text/css" media="screen">
<!–
@import url(main.css);
–>
</style>
Or specify @media rules for those declarations that need to be specifically changed for a different medium
<style type="text/css">
@media print {
/* your styles */
}
</style>
I use from 1 to 4 , but the i don’t use the last. i ll use in future projects
Thanks for a great article! Interesting debate about point 5 – I use import rules all the time and they can get rather sprawling (especially when coding for Drupal) – How many external stylesheets is too many? is there an optimal number to balance efficiency and performance?
Thanks, this is a great post, point 5 is barely new for me…
Agree 100% with Soh … after deigning the front end for a portal system, the CSS grew to over 6-thousand lines Oo That is WITH short-hand, grouping, etc. Breaking everything into little chunks (typography, portal layout, portlet layout, color-schemes) really made everything that much more simplistic and easier to work with / find what you need.
Another thing I found useful is to comment your CSS. If you put in a “trick” or a work-around, comment in your CSS why you did it. That way in the future if you need to change your styles, you can better understand why certain things were done the way they were. It can really reduce bugs in the future :)
Great post and keep up the great work :)
{pats rino on the footer}
I use this all. And I would like to add compression. Use YUI Compressor (or something similar) to compress your CSS. YUI Compressor will remove all whitespace, line breaks and other not-necessary characters. Everything will be a single line.
Therefore, you should always make a backup (I put mine in a folder called ‘uncompressed’) before compressing.
I heavily comment my CSS to make sure that the shorthand and one line coding is more manageable. But to each their own for code formatting style. If it works and is compliant then who is anyone else to judge.
@danny: I guess this is only relevant if http 1.0 is used, right? I mean, http 1.1 uses one TCP connection for multiple documents. I mean, I like the idea to split up large, single StyleSheets into multiple smaller ones. It is easier to read and modify.
@danny & #5: I split CSS files up whenever possible if there is a separate use for each page. I do not use any sort of @import and instead call from my header. This way I can load page specific CSS files. Loading cart.css on a home page does not make sense, nor does loading checkout.css on a product page.
With my apps, I keep several css files but allow the server to combine all the css files before sending them to the client, so only one http request is needed. This file is cached by the server, so it is not generated fresh for every client request, which makes it super quick. In Rails you would use something like this:
“payment” %>
Which combines “shop.css”, “cart.css” and “checkout.css” in to one combined file: “payment.css”
For more detail: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html
Oops, that didn’t display correct, but here it is without the start and end symbols:
stylesheet_link_tag “shop”, “cart”, “checkout”, :cache => “payment”
Best to just check out the link.
Working with multiple CSS files is a lot easier on a big project agreed. Timothy also makes a valid point. I was going to mention that. Use a CSS compressor. Keep a main copy of your file, duplicate it, compress the duplicate, and use it on the site.
All great points and tips! Thanks!!
As a developer, its nicer, easier, and faster to work on code that has lots of whitespace (easy to read) and is split up into multiple files for easy appropriation/management. That goes for CSS and JS alike.
But your code should never go out to the browser in this fashion. There are many great tools for combining and compressing JS and CSS, and you really should use them. YUI has a CSS compressor, and there’s also JSMin (have a google).
The same goes for your markup – you can parse it to remove unnecessary whitespace, comments etc. to reduce the byte-size payload to be delivered to the browser.
Comments are great, and are really useful for in-line documentation, but they should never go out to the end-user (especially in your JS – comments can help hackers find exploits, for example) so they should be stripped before the code is served to the browser.
Perhaps some of these measures are a little extreme for a quick and simple personal WordPress site, but they’re absolutely essential for sites that attract a lot of traffic, handle users’ personal or sensitive information, and/or need to perform exceptionally well.
Pixelz: you really should have just one HTTP request for all your JS and just one HTTP request for your CSS. You can also use CSS sprites to reduce the number of HTTP requests for non-content (i.e. presentational) related images.
Great tips, I’ve actually been working on this for the past month or so and have gotten my css code dramatically short, I also use one line coding, instead of putting each rule in a new line. easier to see and find ids and such.
Well, if the ONLY reason you want multiple CSS files is for your own ease of use… that’s a bad reason to pummel the server.
Internet Explorer is a nasty creature. It RE-REQUESTS EVERY FILE on EVERY page-load. Every time you step between pages, it sends new HTTP requests for ALL files, even though they may have been cached 1 second ago!
It sends HTTP GET IF-MODIFIED-SINCE commands, so it only receives the data if it has changed.
For this reason, if you have 6 stylesheets, you will get 6 stylesheet GET requests EVERY page load for EVERY user. It’s not a good idea at all.
Instead, if you INSIST on having modularized stylesheets for ease of coding, keep all styles in /styles/*, then write a script in PHP/ASP/Perl/whatever that merges all files and writes them to /styles.css so you just run it every time you’ve changed styles.
If I was the server admin, I’d rather prefer you did something like that, than pummel my server 6 times as hard as it has to.
Very cool tips guys, there always comes a time when we need to take a look at our stylesheets and get reshaping.
Good examples! Great tips – Thanks.
Great summary of essential techniques, and a must-read for novices. But, I agree with Danny about #5 slowing down the page's load time due to the extra http requests. There is a way around this by creating a php file with includes for each css file, but it's a bit of a trip: <br /><a href="http://www.websiteoptimization.com/speed/tweak/suture/">http://www.websiteoptimization.com/speed/tweak/suture/</a><br />I think it's simpler to just keep them all in one sheet.<br /><a href="http://thespinarounds.com">Ryan</a>
Some great tips here, thanks.
Step #3: keep in mind that combined classes per element are ignored by (of course) IE6. Only the final class in the chain will be selected and applied. Fine if you are coding for modern browsers, but potentially tricky if you require legacy browser support.
Very useful techniques, thanks for sharing with us.
Really enjoyed this post and like how it is something we can use day to day in our programming.
I would have said more about selectors tho as these can be very very useful.
C
Nice articles and thanks.
very nice article, thanks to share.
Great info about grouping css properties. I’ll definitely doing some code grouping and trimming in my stylesheets after reading this!
Nice tutorial. Thanks.
Thanks Soh
Your explanations are clear to understand for every one.
I also use different css files for different parts of the sites, layout.css, cart.css etc.
So we can deliver the right css files to the right part of the sites.
I believe it is more easier to control and maintain.
Good information thank you I’m learning something new every day the information like this.
looking for css optimization, and found this page. page bookmarked.
Interesting article. the more white space you have in your styles, the easier it will be to maintain, depending on the complexity of the site.
Benga creative
Really Cool man!!! I am really grateful to u for your site, thanx a lot….
Very professional. I really appreciate what you have experienced skill,sharing with us!
Awesome post! Good tips! I would also have to argue though that when designing, it might be a good idea to have multiple stylesheets to keep everthing organized (I’m practically OCD, so I’ll usually have several sheets for a project), but when you deploy your site, the CSS should be condensed down into the least number of file. As an added bonus, and possibly number six on your list, compression. I guess you could argue that it’s not optimization, but shaving some KB’s off a stylesheet is a great way to decrease load time on a site (Only slightly though, now-a-days everyone has DSL or HSI so a few kilobytes don’t make much of a difference). But anyway, I enjoyed the post. Keep it up!
Nice! Thx…
I agree with most of this article, except that you really shouldn’t @import. Apart from the fact that CSS should generaly be small enough to fit in a single file – the import directive causes the browser to send out more requests, that means slow page loads, but also more outgoing traffic from the server (even if you cahce and expire like you should, some clients will still pull the files on every load).
What you really should be looking into is code that will splice all your seperate CSSs into one for production. Plenty of projects (both commercial and open source) do that.
What If a page requires just 5 basic classes of css to show up properly.. by combining all the css of your website you are making that specific page load the complete css file for no reason.. I agree with the @import functionality.
Great Article.. Thanks…
great tutorial for learning css. thanks a lot.
Perfect CSS optimizer:
http://www.optimizecss.com
rt: Perfect CSS optimizer:
http://www.optimizecss.com
VERY cool!
Another online css compressor
http://www.miniwebtool.com/css-compressor/
Don’t use @import: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
Speak Your Mind...