Tips to Write Better CSS Code
Nov 4th, 2009 - 25 Comments »
Posted in CSS

CSS is a language that is not difficult to master, but if you use it for a large project, it can be very difficult to manage if you do not follow a defined approach while writing CSS code. Here are few tips that will help you write better and easy to manage CSS code.
1. Don’t Use Global Reset
Using global reset to remove default margin and padding from all HTML elements is a strict no-no. Not only it is slow and inefficient way but you’ll have to define margin and padding for each element that needs it. Instead use subset of CSS Resets like one from Eric Meyer.
Not Good
*{ margin:0; padding:0; }
Better
html, body, div, dl, dt, dd, ul, h1, h2, h3, pre, form, label, fieldset, input, p, blockquote, th, td { margin:0; padding:0 }
table { border-collapse:collapse; border-spacing:0 }
fieldset, img { border:0 }
ul { list-style:none }
2. Do not use IE Hacks
Though CSS hacks might be useful to maintain consistent look of the website over older browsers like IE6, but they can be problematic for newer versions of IE as newer versions like IE8 do support CSS standards to a good level and using hacks might break out the layout. You should use conditional statements instead to target specific versions of Internet Explorer.
For example, using the below lines of code within your <head> tag will load the iestyles.css file only when browser is Internet Explorer version 6 or less.
<!--[if lte IE 6]> <link rel="stylesheet" type="text/css" href="styles/ie-styles.css" /> <![endif]-->
For information on conditional comments, refer to the quirksmode article on CSS Conditional Comments
3. Use Meaningful names for IDs and Classes
Suppose you define your sidebar styles using class .leftbox and after some redesign, you float it to right, then would it be meaningful to have leftbox as name for right floated box. You should put some thought before declaring classes and IDs for elements so that they are meaningful and easy to understand later.
4. Utilize CSS Inheritance
If multiple child elements of a parent element use same styles on your web page, it will be better to define them for their parent element and let the CSS inheritance do all the work. You’ll be able to easily update your code later and it’ll also reduce the CSS file size considerably.
Not Good
#container li{ font-family:Georgia, serif; }
#container p{ font-family:Georgia, serif; }
#container h1{font-family:Georgia, serif; }
Better
#container{ font-family:Georgia, serif; }
5. Combine multiple Selectors
You can combine multiple CSS selectors into one if they have common style definitions. It’ll save you time and space.
Not Good
h1{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
h2{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
Better
h1, h2, h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
6. Use Shorthand Properties
Utilize the shorthand properties of CSS to quickly write CSS code and reduce file size. Shorthand notation can be used for margin, padding, border, font, background and also for color values.
Not Good
li{
font-family:Arial, Helvetica, sans-serif;
font-size: 1.2em;
line-height: 1.4em;
padding-top:5px;
padding-bottom:10px;
padding-left:5px;
}
Better
li{
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
padding:5px 0 10px 5px;
}
Here’s a complete guide to CSS shorthand properties.
7. Organize CSS Code
Organizing your CSS code in a certain pattern will make it easier to find things at later time and save you a lot of time looking for a specific style definition.
Here is a sample organization that you may use:
/*------------------------- CSS Reset -------------------------*/ /*------------------------- Generic Classes -------------------------*/ /*------------------------- Layout styles -------------------------*/ /*------------------------- Section specific styles -------------------------*/
8. Make CSS Readable
Writing readable CSS will make it easier to find and update a style declaration later. Either group all styles for a selector in one line or each style in its own line with proper indentation. You can also combine these two techniques together.
/*------------------------
Each Style on new line
---------------------*/
div{
background-color:#3399cc;
color:#666;
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
height:300px;
margin:10px 5px;
padding:5px 0 10px 5px;
width:30%;
z-index:10;
}
/*------------------------
All Styles on one line
---------------------*/
div{ background-color:#3399cc; color:#666; font: 1.2em/1.4em Arial, Helvetica, sans-serif; height:300px; margin:10px 5px; padding:5px 0 10px 5px; width:30%; z-index:10; }
9. Add proper Comments
Comments can be used to separate different sections of CSS code
/*--------------------
Header
-----------------*/
#header{ height:145px; position:relative; }
#header h1{ width:324px; margin:45px 0 0 20px; float:left; height:72px;}
/*--------------------
Content
-----------------*/
#content{ background:#fff; width:650px; float:left; min-height:600px; overflow:hidden;}
#content .posts{ overflow:hidden; }
#content .recent{ margin-bottom:20px; border-bottom:1px solid #f3f3f3; position:relative; overflow:hidden; }
/*--------------------
Footer
-----------------*/
#footer{ clear:both; padding:50px 5px 0; overflow:hidden;}
#footer h4{ color:#b99d7f; font-family:Arial, Helvetica, sans-serif; font-size:1.1em; }
10. Order CSS Properties Alphabetically
This might be a difficult way to write CSS but it’ll make it easier for you to find out any property easily at a later stage.
div{
background-color:#3399cc;
color: #666;
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
height: 300px;
margin: 10px 5px;
padding:5px 0 10px 5px;
width: 30%;
z-index:10;
}
11. Use External Stylesheets
It is always a good design practice to separate content from presentation. Place all of your CSS code into external stylesheets and use the <link> to reference stylesheets within a web page. By placing CSS into external files, you can easily update your styles later at one place instead of looking into html templates or files for styles.
Not Good
<style type="text/css" >
#container{ .. }
#sidebar{ .. }
</style>
OR
<li style="font-family:Arial, helvetica, sans-serif; color:#666; " >
Better
<link rel="stylesheet" type="text/css" href="css/styles.css" />
12. Split CSS into multiple files
If you are working on a large web project that has multiple modules, each with different set of styles and looks, it will be better to split your CSS files into multiple files based on the module they are applied to. You can separate stylesheets like, one for reset, one for layout, one for generic classes and one for module specific styles. This technique will let you organize your code easily in a large project but loading multiple CSS files means more HTTP requests and slower loading time, this is where Bridging CSS files come to rescue. Create a separate CSS file and import other CSS files into it.
@import "style/css/reset.css"; @import "style/css/typography.css"; @import "style/css/layout.css";
13. Compress CSS code
Once you are ready to deploy the web design project, compress your CSS code using tools like CSS Compressor to reduce file size and improve loading time of webpage.
14. Be Consistent in Writing CSS
When you work on multiple web development projects, it’ll be a wise decision to choose a particular way of organizing and formatting your CSS code and stick to that way for all your projects.
I hope these tips will help you write better and manageable CSS code. If you would like to share a tip or two, feel free to add your comment below.
Share
Subscribe to Full RSS Feed
If you found this article
useful, then consider subscribing to our
RSS Feed or
e-mail updates to stay updated with
latest Web Design/ Development articles. You can also follow @webdevplus on twitter for latest updates.
25 Responses (Add Your Comment)
Comments are closed for this post.
Lots of good suggestions. thanks
Great! Specially #10 (that I use most) but all of them are must-have-in-mind for beginners and masters.
Tks!
Very helpful advice, including the links. I hadn’t used #12, but will use it on my next project.
Really useful tips. I use this methods in all my coding
That was a great read! Already know / use most of these techniques, but some were great to know.
Thanks for sharing and keep up the great work
.
Persoanlly, I like to write my CSS all on one line. It’s neater to me and easier to find. I have difficulty reading CSS when it’s not written like that. (probably because I’m not used to it anymore) Great organization tips though
Nice!
But I think point #12 is wrong. Even if you bridge those stylesheets in one using @imports it will still have the same number of http requests, in fact, one more http request for the holder stytlesheet.
Try it and see using the yslow in firebug or using tamper data
Thanks Mustafa,
#12 is for better organization of CSS code to ease development, once you are ready for deployment, it’ll be better to reduce the number of HTTP requests for CSS files by combining them and then using compressing tools to reduce their size.
Do not use #12 unless you like unexpected results in IE.
I rarely use CSS resets.
I’ve never had issues using * {margin: 0; padding: 0;} either~
So for me they aren’t all that bad :-p
Yet another great post! I’ve had most of these covered on my CSS coding, but the I gotta take a look at those shorthand properties, I’ve been way too verbose on the properties
number 5, your better example could be condensed more. why the gap?
awesome tips. will bookmark this page. thanks for sharing!
These are good rules to write CSS by and I follow a few of these methods already. I have to disagree with the first one about not using a reset though. I use a slightly altered version of Eric Meyer’s CSS Reset Reloaded with every project. I prefer to reset the marging and padding because each browser tends to handle each of them a little differently. I don’t mind having to set my margin and padding for each element because the majority of the time I cascade the padding/margin for container elements. It’s just personal preference really.
Also, I completely agree with splitting your style sheets up but I do it a little differently. I group my reset, page structure and phrase element styling into their own stylesheet, and then for separate parts of a website (in most of my cases, modules for a CMS), I write into another stylesheet. So I generally have my scree.css file and then my modules.css file.
I love the @import method because it’s easy and clean, but it can sometimes give unexpected results. I prefer to link them because I can’t find any glaring reasons as to why I should use the @import method over it. I almost always only use 2 CSS files at the most, so it’s not a whole lot of HTTP requests.
I’m a little funny when it comes to writing ‘readable’ CSS. If I’m writing styles for an element and there isn’t a lot to it, I’ll normally put it on one line because it’s quicker and easier for me to sort through. I use Coda on the Mac and it does automatic code completion. On the other hand if the element requires a lot of styling, I break each declaration onto its own line.
The rest of these are good advice for both the novice and the expert, especially organization with headings, etc. I think more designers and developers need to practice this. You have to always think in the mindset that you are not the ONLY person that is looking at these stylesheets (even if you are the only one looking at them). You never know how the future goes. You may look back at it in the future and say ‘wtf was I doing?’ Also, another developer might have to add to or edit it in the future, so be courteous and divide up your elements. I usually divide by phrase elements, page structure, re-usable classes, etc.
Another good thing to possibly add to this list is to use a key in the top of your stylesheet. I find this to be really helpful. For example: Say your website uses a lot of different colors. Nobody can remember all of those hex codes. So put them in the top like so:
/* Color Code */
red — #ff0000
purple — #990099
orange — #ff9900
Thanks Daryn for this elaborated comment
and you are right, color codes should also be defined using keys
Great CSS-stuff !
Big Thanx.
Thanks for adding this article, its frustrating when developers are coding to the beat of their own drum not realizing that another devloper may have to work with their code…great article
Before using @import to modularize your CSS. You should read this test by Steve Souders…
http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
In the end, according to his findings @import can either break parallel downloads or be unpredictable in IE and the best is still link to external CSS files.