Squeaky Clean CSS
I thought I’d share a little bit of what I’ve learned from noodling around with stylesheets these past few years. Here are some basic organizational practices I try to follow. ( Much of this might be old hat for you, and if so, just think of it as a refresher. I run into enough messy stylesheets that I thought this might be of some interest. )
Grouping Your Styles
Group your styles into categories (ex. layout, typography, forms, so on) and visually seperate them in your css file. A title and table of contents doesn’t hurt either:
/*
HuddleTogether.com Screen Styles
Table of Contents:
layout
typography
forms
*/
/* layout
----------------------------------------------- */
/* typography
----------------------------------------------- */
/* forms
----------------------------------------------- */
Choosing Your Categories
Even though I do have some common practices, I don’t have a ‘template’ for how to breakdown styles into categories.
For starters, I almost always have layout and typography categories. With typography defining the sitewide look and feel. Depending on the complexity, I may break out the table and form styles into their own categories.
Next, I address the physical sections of the page with their own categories: header, sidebar, content, and footer for example. Lastly, I collect the page and content section specific styles and place them in their own category (and sometimes subcategories).
Importing Stylesheets
Another method is to categorize the styles and place them in seperate CSS files which are all imported by one main CSS file. I find this method good in theory but it can lead to overlapping styles, specification issues, and general confusion if you’re not very careful:
@import url("layout.css");
@import url("typography.css");
@import url("forms.css");
Linebreaks and Indenting
When styling multiple tags, ids, or classes with common attributes, display each on its own line. Also, indent closing braces. Both these actions keep the left column clean so you can quickly skim your stylesheet:
h2,
h3,
h4 {
font-weight: bold;
padding-bottom: 1.5em;
}
h5 {
font-weight: normal;
font-size: 1.5em;
padding-bottom: 0;
}
Descendant Selectors
Use descendant selectors generously and consistently to keep your styles grouped neatly and CSS specificity in check:
#header {}
#header .logo {}
#header .logo img {}
Quick Disable
A trick I use all the time to temporarily disable a style attribute involves simply adding an ‘x’ in front of the attribute name. It’s safer then cutting and quicker then commenting out:
#footer{
border-top: 1px solid #e5e5e5;
xborder-bottom: 1px solid #e5e5e5;
}
Keeping Track of Divs
Quick HTML pointer. For div tags that stay open for a number of lines, add a small comment after the closing tag about the opening div’s id or class:
<div id="content">
<h2></h2>
<p></p>
<p></p>
<p></p>
<p></p>
</div><!-- end #content-->
Those are handy tips, sometimes I use them, but often forget… Thanks for remembering them to me :-)
Some great tips, especially the one about indenting the closing braces. :)
Useful, cheers. Only thing I don’t always do is use line breaks between ids or classes with common attributes.
I am in the habit of dividing up styles based on page sections, rather than by style categories. So for instance, I’d split up a CSS file based on main content column, side columns, footer, header, etc. If the site is big enough, then I create a global style sheet that contains things like the header and footer, and then break out each unique page style into its own style sheet. I find that this helps you see all the styles for a particular page area at a glance.
some really nice tips. I’ve been using a few myself the past few months. Helps ALOT!
what happened to the lightbox gallery?
Learned a lot from your site already (your css in particular). Hadn’t touched html since css first came out and I hadn’t used it yet. Decided to build something when I came across a reference to your lightbox script and felt inspired.
Nice to see how much easier it is with css. Didn’t think I’d concern myself with cross-browser compatibility, hoped that was a thing of the past. Haven’t used anything other than IE since the old days. After setting up a simple site, I installed ff & ns on another pc and was shocked to see how differently they rendered it. Disappointing to see I’d still have to view in other browsers just to verify I’d get what I expected. Had to keep everything inside the #wrapper if I wanted to get the same results in every browser.
Now, I know I don’t have the chops yet to correct you, but…
Shouldn’t your reference to blank.gif point to an actual file? Seems to work either way, but I put one there with overlay.png anyway since I’m gonna be looking for one. I think you should include one with your files to download. Anyone can make or find a one pixel transparent gif, but I grabbed one here:
webfx.eae.net/dhtml/pngbehavior/blank.gif
Thanks for everything, looking forward to the next version.
Great article! I find it very usefull. 10x ;)
very cool
Categorising style definitions is a must, great post.
However, some of you may have realised, indenting html tags could cause problems in some browsers - as each browser processes whitespaces differently.
Quoting from my own experiences, Mozilla based browsers work great with indented html tags (apart from a few tags like ). However, IE version 6 and 7 (PB2) represent a few newline characters as which gives me a lot of headaches.
Sorry, the comment section takes in html tags which were mentioned in the previous comment:
…. a few tags like (pre)).
…. newline characters as (br) which …
Interesting tips. I think I can improve on #5 though. I add “disabled-” to the front of my disabled attributes. Then, if I want to find a particular disabled attribute, I can simply search for “disabled-”. It’s much more effective than trying to find “x”. Of course, it’s longer to type “disabled” than “x”, so perhaps “x-” would be a good compromise.
tg-
It’s a good idea to design sites for Firefox first, and then fix the bugs in IE. Firefox has much better CSS handling, so you won’t end up relying on some unknown IE bug for your site to display correctly.
Personally I always check code in both Safari and Firefox. Since they both use different rendering engines, if things look the same in both then I can reasonably assume that the CSS is being interpretted correctly. On a PC you could use Opera for this purpose, but I find its CSS support to be inferior to Safari, but much better than IE.
Overall a nice basic tips list.
A couple of comments:
As a programmer, Indenting the closing braces would drive me nuts and seems dosent seem to add any real value.
It is important to note, in regards to commenting that “visually seperate them in your css file with some fancy commenting.”
and usng
“/* layout
———————————————– */”
adds unwanted size to your css document.
great tips and comments above. I use many of these suggestions currently and love too keep css clean and orderly. i agree with using firefox as a base…this has saved me much trouble in the long run.
thanks again,
james
using comments in between divs like you suggested can trigger nasty bugs in IE (very rarely, but enough for me to have stopped using them now). I ran into this on a project not too long ago.
http://www.positioniseverything.net/explorer/dup-characters.html
There’s the info on it.
great post. really handy for persons (like me :)) who loves to forget small tips.
cool
when i’m developing a website, i uses alot of different stylesheetss (15, 20 or even more)
The reason is because is don’t like to scroll in my css files. And you don’t need all your styles all the time; once the frame of the wite has been set,I save it as frame;css and start for ex. topmenu and save this etc … At the end, I just combine them to 2 or 3 sheets and publisch them.
Caught the link off Digg. Awesome stuff.
Nice tips, and I think this could be broadened to any code really. Never underestimate the usefulness of cleanly formatted and commented code. =)
gimme 7 more!
Nice work, thanks for the examples. Wayne @ http://sfsurvey.com
Wow. I guess great minds think alike. I’ve already been using 1, 2, 3, 4, 6 for well over a year now. 5 and 7 are very clever, though.
Thanx a lot, im glad to see that i already use much of the tips you have given (saw them first somewhere else hehe)
So Simple, yet so effective
good stuff, thanks
Hey, I’d just like to thank you for the inspiration you and this website has given me. I’m a little bit obsessive compulsive (Not much, I guess it’s just perfectionism), so I’ve always been really picky about my code and website designs. I’ve learned something today by just checking the source of the site (And also noticed the really clean code :P), which was the multple classes on one element.
Great job on the site - it also inspired the layout of my current site (http://www.mynimal.net/). Great job, and keep it up. :)
When coding i do most of this, Except when adding an ?x? in front of the attribute name. This is much more safe than just deleting it all together.
Thanks for the topic.
Btw absolutely love your site. Good Work!
Best Regards,
James
You should also put in a tip about contrast, although it seems that contrast is something that this site is lacking so perhaps you haven’t heard of it.
Robble-robble!
Pretty good rundown - I didn’t know about #5!
Personally I like to put similarly natured attributes on the same line, to save on file size and help organize really lengthy selectors.
Thanks for the great tips - well done!
Thanks… as a CSS newb this stuff is great.
I’ve gotten in the habit of (mostly) alphabetizing my css styles. To keep like things together alphabetically, I’ll name them accordingly such as: “sidebar”, “sidebar-this”, “sidebar-that” It’s very helpful for (for me) finding specific items.
I’m not knocking rule #1. I’m sure if I was in that habit, I’d swear by it, but I’ve developed (for better of for worse!) a different habit. It seems that most of the css i look at when I’m curious “how’d they do that” tend to follow rule #1…. perhaps someday I’ll convert =)
Believe it or not, I’ve actually started using all of these in my projects, but not because I’m some sort of all-knowing master; it’s because I have personally run into issues where following these tips could have saved my ass. Thanks for the reminders, these tips are all very useful.
I appreciate your summary. find your technique useful. I have seen some but yours is much complete what more the following comments adds further tips to it–that’s what forum is all about. Thanks.
A nice summary indeed, I’ll have to remember a few of these as I already use some of the others. Thanks :-)
Great tips! I’ll start using them right away!
Good tips!
Grouping is a must, especially if you edit your CSS by hand. I prefer a grouping method I’ve learned from stopdesign.com (I think): you split the styles into categories like HEADINGS, LINKS, TABLES, FORMS, LISTS, etc, that way if you’re looking for a certain element, you know where to find it.
boring
Hi,
I’ve seen a similar article at,
http://erraticwisdom.com/2006/01/18/5-tips-for-organizing-your-css
He has some slightly different tips, for example he indents his descendent selectors;
#main_side {
width: 392px;
padding: 0;
float: right; }
#main_side #featured_articles {
background: #fff; }
#main_side #frontpageads {
background: #fff;
margin: 8px 0; }
as opposed to
#header {}
#header #branding {}
#header #branding #logo {}
In the past i’ve seen a lot of people whinge about people stating the obvious with simple tips like these, but i think its great to see a standard begin to emerge. Does anyone have a suggestion on creating a widely supported standard from “common sense” tips such as these.
Darn! the indentation was stripped out after I submitted the note..
Nice tips but to be honest a little more contrast in your design would’nt hurt and wouldn’t make reading more difficult.
Well, being a professional in the graphic world and highly regarded as one of the key players in the graphic world, I find these tips are ones that I employ regularly within my expertise in the graphic world, however they are good hints to provide for new comers or amatuers in the web design world.
Good Job! Well Done + Very Neat Layout! Sexy! Iloveit!
Speaking man to man, did you intend for these tips to be standardized practice only to reformat the website code so as play the role of a thorough practitioner in the web design world player? ;)
Geez that Belvan is highly regarded by all of us. What a guy. He’d give you the shirt right off his broke back.
lots of LOL @ #45 and a few more at #46.
classic.
Thanks for commenting with notes, links, ideas, etc. I do soak it all up, good and bad.
#14 DM - About adding unncessary size to the CSS file with the ‘fancy commenting.’ I find it to be a worthwhile trade off, a few bytes for some clarity.
#30 and #44 ozh - Fair point about low contrast. It has been turned up a notch.
“A trick I use all the time to temporarily disable a style attribute involves simply adding an ?x? in front of the attribute name. It?s safer then cutting and quicker then commenting out:”
You’re kidding .. right?
I agree with most of the tips, and use most of them already. However, I suggest you change your example for the “Descendant Selectors” tip. Usually, there is no need to use descendant selectors when you are using element IDs. So, for example, “#header #logo” is not necessary; “#logo” represents a unique element and there is no need to complicate the selector by restricting it fruther with the enclosing element’s ID.
I suppose you could have a rule for when the logo is in the header, and another rule for when it isn’t in the header. I suspect that doesn’t come up that often, however. Using a descendant selector will waste some time as the engine checks the document hierarchy. It’s probably not a big deal, performance-wise, but if the simpler rule is also faster, stay simple.
Obviously, using descendant selectors with element names or class names is very useful. So, “#sidebar LI” is a good way to set the style for LI elements that are in the sidebar.
Those are great tips, thanks for sharing them :D, I’ll implemented from now on, specially “..” I always have trouble with that.
J read somewhre anotther good advice to write your categories uppercase so that it is easier for you to search and navigate trought your stylesheet, thanks
Hi Lokesh. I am using your LightboxJs script on my site. On your site it says that you are always on the lookout for freelance work. I was just wondering if you would be able to share the theme that you use for this blog. Its clean and simple. Ofcourse, credits and the like would go to you. If you are unable to share it then np, maybe you could give me guidelines on developing a theme like this for wordpress. Thanks
i’m a bit wary of subscribing to one standard of css.
it’s all really new still and a lot of folks i notice tend to complicate things a lot more with some massive css document, when the initial motive of css was to SIMPLIFY.
“Descendant Selectors”…great example.
remember the days of debugging a nested table within a nested table within a nested table…..?
think about the next guy/gal who’s gonna work on your site a month after that tragic ferry accident that takes your life.
css is way cool and way sexy, but i think a lot of folks are making it way too complicated.
that said. great article.
the only thing i would comment on would be indenting. i think you may consider indenting both the opening and closing brackets to keep that left column clean as clearly illustrated in your “quick disable” example..which i’m not sure falls under the category of “clean solution”.
just my $.02
boogie on
Really great tips as everyone has noted above.
I have always made it a habit to seperate my code and make it legible for the next coder / designer / developer.
With these great tips, it sure will help for the future.
Regards
www.esc-ctrl.co.za
#50 Transom - Very good point about the descendent selector example.
Thanks for for the comments everyone, and again, these are some techniques I use, and not de facto standards. If you have ideas that can improve the article, let me know.
great tips.
i got ya marked on my blawg as well.
http://www.jammo.net/2006/03/12/grouping-your-styles/
nicely done.
someone above mentioned this article:
which i am implementing as well:
http://erraticwisdom.com/2006/01/18/5-tips-for-organizing-your-css
Some very good tips here. I’ll have to make sue of some of your code organization advice in future projects.
I’ve made a habit of practicing a variation on your “categorize and import” strategy for style sheets. I categorize my styles into layout, typography, and print. Then, Instead of importing them all into a master style sheet, I link them all separately from the XHTML document, specifying different media types for each:
layout: screen
typography: screen, print, projection
print: print, projection
This makes the setup of the print style sheet — something I used to have trouble with — extremely easy. I just ignore certain web-only UI elements, share typographical hints with the typography style sheet, and most of the work is already done. :-)
That’s the most valuable thing I’ve read all day. Thanks for sharing your excellent CSS strategies.
These are great tips, I never thought of simply using an X at the start of a line to disable its effects.
I love seeing other people’s ideas on how to work more efficiently, especially when they really work and help.
I get so flustered when people name their css rules “box” or “content”. Box what? Content what? Name your styles to be specific like “box-that-contains-content-crap” and “content-that-someone-might-give-a-crap-to-read”.
Awesome tips! Don’t forget to use selectors so that you can apply styles to a specific child such as
.MichaelJackson > .LittleBoys {height:56in;}
I like your tip about giving multipe selectors their own line, but I *hate* working on stylesheets where each rule inside the braces has been given its own line. Not only does it mean a lot of unnecessary scrolling, but also searching for particular rules is useless. If I want to find all the elements with a border, a hypersearch for ‘border’ just yields a lot of lines that, yes, say “border: …”. Not a lot of use. When the whole ruleset is on one line, you find out which selector it applies to and what other rules are being applied.
I got this from Eric Meyer, so it’s not completely mad.
Great site! Thank you! I enjoyed it!
I defenetly cured from boring wasting of time as soon as surfed in to your site!
#65, u rule
Not too important, but be careful with css import using double quotes because Mac IE doesn’t like it. Its better not to use any quotes.
http://www.dithered.com/css_filters/css_only/index.php
Just want to add a note for what @Thriller was saying, just remember that its not IE-friendly, but then again… since when was IE friendly? =)
Wonderful!
Writing neat and tidy CSS is important.
i like the quick disable thing - sure it doesnt validat but its only for the ‘in-development’ phase presumably
however, having cleared out the left column by indenting th styles already would the x work equally well in that indent space - makes it even easir to scan for disabled styles that way? im guessing too many browsers will correct that as an error like they let you get away with not having a ; closer sometimes - pita
I’m really impressed!
buy phentermine | carisoprodol | tajny |
Best site I see. Thanks.
[URL=http://s3.phpbbforfree.com/forums/index.php?mforum=kkarsha]adipex[/URL] [URL=http://vvarder.cba.pl/adipex.html]Territoire[/URL] [URL=http://vvarder.cba.pl/alprazolam.html]alprazolam[/URL]
May we exchange links with your site?
ambien http://vvarder.cba.pl/ambien.html hydrocodone http://partizzanka.cba.pl/hydrocodone.html lorazepam http://partizzanka.cba.pl/lorazepam.html
Hello Jane, great site!
Thank you! I enjoyed it!
duh! the quick disable looks so obvious written down, yet i’ve been commenting css parts for years… great article, man. appreciated.
HI!
I have copyed you style
is you disagreed
i will remove it
because i enjoy it very much
wonderful!
you can visit http://medcl.net
please contact me if you don’t like …
Nice tricks, a big help for the disaster, ha,ha,ha … i knew every one, except that the one with the x in the front of an atribute, ha,ha i always use comments… :) because i’m lost in code in some cases and could not find the x later…. XD
what’s that?
Huh??
Thats not strictly XHTML 1.0 valid!?
… …. =
;-)
hh
Another little tip:
When I’m creating styles for an element and scratching my head trying to work out where it actually starts and finishes on the page, I temporarily add a bright red border style to the CSS:
#myElement { border:1px solid red; }
gf
IT’S SO….SO….SO….CLEAN, I LIKE THE LIGHT FEELING~
This are very useful tips and easy to follow. Thnx a lot.
www.noremedy.net is my site
That is all css, iv been doing it 3 days now.
Your tips are awesome
xscs
xscs
One useful thing for arranging color schemes
I was recently working on a project. Just before the project was complete my boss asked to change the color scheme. It was a real pain in a5s to find and replace all the colors with new values. So I learnt a lessons: type all the colors at the beginning of document with a description for them like so:
/* Color Scheme
Light BG #E2F6F4
Medium BG #C4D9DE
Dark BG #8AB7C2
Brdr & Text #115566
*/
It really helped me. Hope someone else finds it useful.
Improvements and suggestions are welcome.
I thank you for your comment. http://www.internetmuetze.de
#46 is killing me.
What is a Belvan?
Ray. i think #46, is referring to #45 who’s name seems to be Belvan.
Great tips, I’ve been looking for some simple guidelines for coding clean CSS for a while.
And thanks for the design, I’m currently using the Qwilm theme on my wordpress blog at http://endemoniada.org
Hi,
Thanks for you hints. Do you like to exchange links with us.
My website is:
http://kredite.projekt-opsio.de/
Please mail me.
Thanks for this article… Very useful!
nice one! love lightbox btw cheers for ur hard work
If you really are concerned about doing good style sheet work, you should be focused more on “browser inclusion” than “squeeky clean” sheets. Whats more important…..that more users see your site in more agents or pretty style sheets?
The only item I liked in your list and found useful was the import list. But even thats a bit immature. You should consider revising that for different situations and sheets for different browers and versions. For example IE5, IE6, and IE7 are all different and have different CSS “bugs”, when you are using non-quirksmode layouts. Use the following types of imports to control which browsers get which fixes:
1. @import ‘/styles/styles.css’ - All but NS4 or earlier (PC/MAC), IE4 or earlier (PC), all IE (all MACs only) [use to target IE 5 PC]
2. @import “/styles/styles.css” - All but NS4 or earlier (PC/MAC), IE4 or earlier (MAC/PC) [use to target IE 5 PC/MAC]
3. @import url(/styles/styles.css) - All but NS4 or earlier (PC/MAC) [use to exclude NS4 PC/MAC]
4. @import url(’/styles/styles.css’) - All but NS4 or earlier (PC/MAC), all IE (all MACs only) [use to target all IE’s PC only]
5. @import url(”/styles/styles.css”) - All but NS4 or earlier (PC/MAC) [use to exclude NS4 PC/MAC]
6. @import “null?\”\{”;
@import “/styles/styles.css”; - All but NS4 or earlier (PC/MAC), IE4 or earlier (MAC/PC), IE 5 (PC only) [use to target IE 5 MAC]
7. @media all{(open comment) rules (close comment)} - All but NS4 or earlier (PC/MAC), IE4 or earlier (PC), all IE (all MACs only), special browsers on new MAC OSX [use to target IE 5 PC]
If you want to learn more about CSS fixes and “hacks” for fixing browser CSS bugs, come check oput my site: www.stormdetector.com
Ive got the first Internet Explorer 7 CSS hack that allows you to target IE 7 and many others.
Speaking man to man in the graphic world, i must say: rockin’ suggestions!
And Lightbox is a joy… Many thanks for the awesome works!
Fantastic website… Good resources for learning, easy to follow… Keep up the good work!!! Make your opinion about my resources :)
This has come in handy! I have been using these tips to keep me squeaky clean! Thanks for the help, and I love Lightbox! Awesome work-
Add Comment