erraticwisdom

Categories

View the Archives »

Article

5 Tips for Organizing Your CSS

Working with CSS on my own site’s redesign, freelance work, and my job made me start thinking about the best way to standardize and organize the way I write my CSS. So, I proposed the question to my 9rules friends to collect the best tips from the best designers.

1) This tip is perhaps the most useful because it can apply to both formats of CSS organization that I will describe later. I first saw this on Mike Rundle’s latest redesign of 9rules where he indents descendant and related rules.

For example:


#main_side {
    width: 392px;
    padding: 0;
    float: right; }

    #main_side #featured_articles {
        background: #fff; }

    #main_side #frontpageads {
        background: #fff;
        margin: 8px 0; }

This structure makes it easier to define page areas and how they relate to each other.

Also, the technique can be used when styling specific areas even if the base requires no rules. This can best be seen in the headlines:


h2 { }

    #snapshot_box h2 { 
        padding: 0 0 6px 0;
        font: bold 14px/14px "Verdana", sans-serif; }

    #main_side h2 { 
        color: #444;
        font: bold 14px/14px "Verdana", sans-serif; }

    .sidetagselection h2 {
        color: #fff;
        font: bold 14px/14px "Verdana", sans-serif; }

2) The second tip is to use shorthand properties to keep all parts of a style type on a single line.

For example:


margin:5px 0 4px 10px;

Is much more efficient than:


margin-top:5px;
margin-right:0;
margin-bottom:4px;
margin-left:10px;

Combining properties onto a single line using shorthand properties means that your CSS will be easier to understand and edit.


#test {
      margin-top: 2px;
      margin-right: 3px;
      margin-bottom: 5px;
      margin-left: 9px;
      font-weight:bold;
      font-size:12px;
      line-height:14px;
      font-family:Arial, Verdana, sans-serif;
      border-width: 1px;
      border-style: solid;
      border-color: #000000;
      background-color:#fff;
      background-image:url(bg.gif);
      background-repeat:no-repeat;
      background-position:0 15px;
}

That is almost impossible to edit, but using a few shorthand properties, the chunk above can be reduced to a much more manageable four lines.


#test {
      margin: 2px 3px 5px 9px;
      font: bold 12px/14px Arial, Verdana, sans-serif;
      border: 1px solid #000;
      background: #fff url(bg.gif) 0 15px no-repeat;
}

3) The third tip is to clearly divide your stylesheet into specific sections. Also, by using a flag, you can get to the area you are looking for faster. Before you divide up your styles, it is important to define an outline you are comfortable with as will as a separator format you can notice easily.

A sample format I try to stick to is this:

  • Global Styles – (body, paragraphs, lists, etc)
  • Header
  • Page Structure
  • Headings
  • Text Styles
  • Navigation
  • Forms
  • Comments
  • Extras

And a sample separator that is most easily noticeable for me is:


/* -----------------------------------*/
/* ---------->>> GLOBAL <<<-----------*/
/* -----------------------------------*/

4) The fourth tip is difficult to get used to, but can be invaluable once perfected. It is important that you define the basic rules for each area only once so that the same default value is not being rewritten in every rule. If you know that all of the h2’s will not have a margin or padding, define that on the top level and let its effect cascade as it is supposed to. This helps a great deal if the design requires frequent color changes or other non-structural modifications.

5) The fifth tip is more of a comparison between to major options of organizing your CSS, each with it’s own merits and flaws.

On one hand, you can throw your CSS into a compressor to get a very polished and clean view of your entire CSS structure – each rule on a single line. The advantage of this method is that you can get an easy view of your entire stylesheet without much scrolling. The disadvantage is that it is difficult to edit because many rules will require you to scroll horizontally.

Using the more prevalent tabbing method for organization simply reverses the advantages and disadvantages.

The easiest method is to combine all of the tips above to move the base styles for all elements into a separate section of the stylesheet or a separate stylesheet altogether. This leaves less rule-setting for the more specific elements and allows you to have a shorter stylesheet for your main design.

61 Comments

  1. Matthew Ulm

    Jan 17, 18:38

    Nice article, will use it on my site

  2. Jeff Croft

    Jan 17, 18:42

    Nice article. Good tips, here!

    That having been said, I have to say that, at least for me personally, I find CSS written using all the shorthand to actually be harder to read. I think condensing your CSS to shorthand s a good idea for bandwidth reasons, but I actually prefer to work with and edit the longer versions. I usually wait until I’m basically done to condense things to shorthand.

    I might be alone on this, but that’s my feeling. :)

  3. Nathan Smith

    Jan 17, 18:52

    Re: Jeff’s comment – I usually use shorthand, but will long-hand something if I want to over-ride just one particular thing. For instance, if I’m happy with the margins, except for the top of something, then I’ll use margin-top to tweak it.

  4. Thame

    Jan 17, 19:13

    Matthew: Glad I could help, although I should re-mention that most of these tips are my fellow 9rulers, I just collected them.

    Jeff: I agree with you that a prototype version differs greatly from the finished version. I usually begin with the basic CSS within the HTML page itself to set up the markup and CSS together, then move it to an external stylesheet.

    Usually I keep my font styles expanded and only use shorthand for backgrounds, margins and paddings because it’s easier for me.

    Nathan: Yup, I do the same.

  5. Band of the Soulstripper

    Jan 17, 23:27

    Uh – is there something non-obvious here? If you’ve been using CSS for any length of time, this is all stuff you’re already doing. Hello?

    Interesting how your required fields fill themselves too – I assume that’s a bug?

  6. Justin

    Jan 17, 23:48

    There’s always one in the crowd that has to complain. Why did you even bother looking at an article for “Tips to Organize CSS” in the first place?

    Regarding shorthand, I’m a bit of a mixed bag. I always put all of my margin and padding dimensions on one line, but I usually define font styles with separate lines for family, size, and line height. One thing that I found recently (and was rather annoying until I figured it out) was that there are situations where if a background-color isn’t defined in shorthand with the background-image, it won’t render. I don’t know exactly what caused it as I didn’t test it after getting it working, but I believe it was a floated div with a background image positioned with coordinates (no repeat, so the color was supposed to fill in behind it).

  7. Andrew

    Jan 18, 00:00

    I only use shorthand for short values. It makes it easier to read for me. Though I must say, I have this odd hate for shorthand colors.

    I like the indentation for child styles, dunno why I never did it, but now I’m going to.

    Truth be told, there is no right or wrong way to format your code. As long as I can read it, it’s good enough for me. At some point, you have to realize that the majority of the people looking at your code are other coders, you can leave some of the thought to them. They’re smart too! ;)

  8. Paul Stamatiou

    Jan 18, 00:08

    Great stuff as usual Thame.

  9. Chris R

    Jan 18, 01:46

    Simple stuff really if you’ve worked with CSS for over a year.

    The first rule I always apply is;

    * { margin:0; padding:0; border:0; }

    Then I add borders, margins and padding when I need and not keep writing margin:0 over and over.

  10. Vesa Virlander

    Jan 18, 01:58

    How about “properties should be specified in alphabetical order”, that line is used pretty often in similar articles.

  11. Bramus!

    Jan 18, 02:12

    Is it just me, or are the “tips” posted above so obvious/duuuuh-like that this article totally becomes obsolete?

  12. Anonymous Coward

    Jan 18, 02:18

    I think that as a lone CSS coder it’s fine to say anything one wants in terms of code structure, but when a team hacks up the CSS it usually goes to bits. Unless the CSS rules initially defined by the designer are explicitly tied to the other team members’ paychecks, guidelines fall to pieces when the client comes a-calling. That’s my experience as of this post!

  13. markku

    Jan 18, 02:32

    Regarding tip #4, you can always cascade a default set of properties, and override it in the individual items, if need be.

  14. Alex

    Jan 18, 02:33

    Great tips, I must admit the font shorthand property is pretty complicated – so I generally split that up.
    I did try to split my CSS into positioning and typography sections – and my advice is don’t! It’s too easy to get lost when there are multiple instances of classes!

  15. swape

    Jan 18, 02:39

    Nice article. Many of us needs some rules to code better.

    And there are some idiots here writing a “I know that , duh” comments. Please….

  16. Carsten Rose Lundberg

    Jan 18, 02:39

    I like the article and was happy to see that I’m already doing most of it :-) The ident tip was new though and I’ll start using that for sure.

    One thing I’ve tried on a few occasions is to seperate styling from positioning. So that one stylesheet takes care of styling while another takes care of positioning. It’s overhead in that classes gets defined twice but it makes it easier to know where to look for things and you can delegate issues easier. “You take care of the positioning issues and you correct the styling issues

  17. Richard Kendall

    Jan 18, 02:44

    I agree with Nathan Smith , I use shorthand css now that I am comfortable with it, but if I just want to alter one dimension I’ll put that long-hand as well: margin:0; margin-right:1em; etc.

    It has to go straight after otherwise it may get missed when debugging or altering at a later date. This combines the best of both worlds.

  18. Andy Beeching

    Jan 18, 02:52

    This page is a great place to start for a neutralising stylesheet you call/import before applying any other styles. Also explains why you shouldn’t use the wildcard whitespace stripping rule mentioned above by Chris R (can be more trouble than it’s worth on forms etc…)

    Here

    I do use all the above, but also separate my CSS into four/five stylesheets (initial / layout / typography / navigation/ Content Styles and then for forms and tables as well (when needed).

    Check out content with style for tips on this

    BTW, any chance you can increase the text size in this form, and/or increase it’s size? It’s a little on the small size for writing comments. Cheers!

  19. Dave

    Jan 18, 03:39

    With 20 programming languages, 4 markup languages, 3 spoken languages, plus piano and the ancient board game Go all stuck inside my skull, you expect me to remember the order of CSS shorthand properties, too?

    Sorry, my brain is full. I’ll take explicit coding practices over implicit any day.

    Point #2 is not so happy.

  20. Dan Bailey

    Jan 18, 03:43

    Good article, cheers!

  21. Sergey Koksharov

    Jan 18, 04:07

    It’s seem to be great “Combining properties onto a single line”, but not good for parsing style items.
    Frequently I parse user’s stylesheets (on my sites) to make interactive changes.
    Let compare strings
    1) border: 1px solid #808080;
    2) border-width: 1px;
    border-style: solid;
    border-color: #808080;
    In second case strings parsed more fast then in the first case.
    I think, this article usefull, but in specific chance we can use these suggestions.

  22. Marko Mihelcic

    Jan 18, 04:14

    hm good point, good article Thame,this might be in handy these days :) cheers m8

  23. Brian Heumann

    Jan 18, 04:40

    Good article, thanks a lot for putting all this together.

  24. Jon Dowland

    Jan 18, 05:03

    Generally some good advice: one point about compacting lines, though : in some cases it may prove harder to read. For margins and background placements, for example, I tend to explicitly write something like

    margin: 0; /* no margins at all */
    margin-left: 2em;
    margin-right: 2em;

    ...as I forget the order in which the margins are applied in the one-line case (I could just remember “clockwise”, but I don’t). Same applies for background positioning:

    background: url(...) no-repeat 45px 72px;

    I almost always have to figure out which pixel value is x and which is y by trial and error.

  25. sparsely

    Jan 18, 06:23

    i also like grouping simlar rule types on a line

    h3 {
    position:relative; left:-.6em;
    width:100%; height:1%;
    margin-bottom:.3em; padding:.2em 0 .3em 1em;
    text-transform:capitalize; font-size:120%;
    }

    like:
    classification
    dimension
    whitespace
    other
    text
    background
    border

  26. michiel

    Jan 18, 06:32

    here’s a tip for you: how about using em’s for font-size instead of pixels?

  27. Veracon

    Jan 18, 07:37

    “Combining properties onto a single line using shorthand properties means that your CSS will be easier to understand and edit.”

    Easier to maintain? Yes. Easier to understand? No.

  28. Lee

    Jan 18, 07:46

    Good tips. Thanks for taking the time to write it down.

  29. james McClelland

    Jan 18, 08:44

    Sometimes, when I edit, Iremove the HTML to which some styles apply. Can anyone tell me if there is a program that will scan a stylesheet and remove styles that are not used? I’m thinking like an HTML Tidy for “orphan” css.

  30. ChronoFish

    Jan 18, 09:08

    “Combining properties onto a single line using shorthand properties means that your CSS will be easier to understand and edit.”

    Not at all. I find single line attributes much easier to undestand and maintain (does left come before right, does top come before bottom?) I suppose if you live in CSS land then short-cuts are fine. Or if you are Perl lover then you can’t get enough of them. If you are going to maintain stylesheets in group setting – being verbose tends to introduce fewer errors and can be easier to track errors down. Of course there are exceptions to every rule…..

  31. Loomy

    Jan 18, 09:19

    Those are some great tips. Good work!

  32. Christian Watson

    Jan 18, 09:38

    Two tips from me:

    1) Break your CSS up into different style sheets. For example, one for layout, one for text, one for forms, one for tables, etc.

    2) Organize your properties alphabetically within each rule. This makes your code easier to read and debug as you always know where to look for a property.

    I wrote about this in a little more detail on my blog – Suggestions for Organizing Complex CSS.

  33. James Mitchell

    Jan 18, 10:11

    Thanks for the tips. I already use shorthand and like Nathan and a few others, I’ll use the long handed version for tweaking when necessary.

  34. nuffGigs

    Jan 18, 10:56

    nict tips.. I was planning on getting some type of standard for my css files but never got to it.

    I agree with some of the comments made about coding with standard version and compressing the finished version before deployment.

  35. Jay Ramos

    Jan 18, 11:18

    Another extension of this is thinking about how to organize all of your CSS into multiple files when working with a large site. Then you’ve got alternate stylesheets and media-specific styles and hacks to get around browser irregularities and… maybe I’ll just go back to table-driven layouts. :)

  36. Trams Studio

    Jan 18, 12:55

    Very nice. I will definitely use these tips on all the sites I make. I have been trying to make some sense of my huge CSS documents. But as I build sites, they kinda takes off on their own. Using a pre-built structure will be a huge time saver, and sanity saver! Thanks!

  37. Rob

    Jan 18, 13:06

    Great post! This comes in handy very much for a CSS newbie such as myself. =]

  38. Dennis Bullock

    Jan 18, 13:32

    This is an excellent post and hit the nail on the head that organization is still important for a sites successful outcome. Thanks….

  39. Brad

    Jan 18, 14:23

    Fine as a unification of ideas, but you present nothing new.

    Stop Design had an article on the organization aspect last year.

    The rest is just common sense for anyone that knows CSS at all.

    Good tips for newbs.

  40. Feaverish

    Jan 18, 14:25

    A good CSS editor (like CSSEdit for OS X) can help organize CSS. CSSEdit, for instance, lets you group styles (it adds valid comments before and after the rules, which it understands as groups), and you can then fold or expand those groups to make editing lengthy files much easier.

  41. miscblogger

    Jan 18, 16:34

    Hey thats cool! I will definately use them in my upcomming websites. I really hate how CSS files usually get spagetti coded.

  42. Ian Williamson

    Jan 18, 16:40

    These are very helpful tips. Thank you.

  43. Cully

    Jan 18, 19:22

    I agree that these suggestions are pretty obvious.

    Tip #1 is the only semi-creative tip and I’ve seen it suggested in other, similar articles. Like the community bicycle, it’s been around.

    Tip #2 technically doesn’t make your CSS more organized. It just makes it shorter and, hopefully, more readable. Plus, it’s a basic feature of CSS. Who doesn’t know about short-hand properties?

    If you told a room full of people to organize a group of objects in any way that they desire, I bet that 99% of them would put them into categories. So, if 99% of people, who know nothing of CSS, could come up with the idea of categorization, it’s probably safe to assume that no one needs to include it in a list of ways to organize CSS.

    Tip #4 is a basic tenant of CSS design. If you’ve read anything about CSS, you should know about this.

    A better solution to tip #5 would be to use a CSS editor that can collapse your styles into a single line and expand them when you want to edit. Why run it through a “compressor?”

  44. Stoyan

    Jan 19, 07:19

    Thanks for this article, very good tips!

    Some time ago I tried to put together some ideas, suggesting more predictable CSS. There I tend to be on the opposite opinion on the use of shorthands, but it really is a qustion of preference.

    To me, the most important thing is consistency. I think whatever organization policy a team chooses, everyone should just stick to it. This way when the moment comes to change something, you know where to find it.

    Again, very good article, I particlulary liked tip #1. Thanks for sharing!

  45. John Bilotta Jr

    Jan 19, 11:36

    Great article!

    I personally have problems with OpenSource backend software like Gallery, that contain CSS defined layouts and the programmer has written his sheet, repeating the same rule over and over for different attributes. It takes me about 5 hours just to get it all together again.

    Thanks for spreading the knowledge.

  46. Thame

    Jan 19, 21:34

    Thanks to everyone for your nice words, additional tips, and constructive criticism.

  47. Sven

    Jan 20, 04:49

    Thanks for this nice article!

    Can I translate this in german and use it on my site?
    I would like to show this my classmates.

  48. Barry Welford

    Jan 20, 10:54

    Help is defined by the recipient, as Peter Drucker said. I found this a useful and clear article. Thanks for that.

    One extra tip might be to use classes more. You can apply multiple classes to say a div. So if you define
    .right {float:right;}
    and
    .italic {font-style:italic;}
    then just using
    < div class = " right italic " > (spaces added to show here)
    gives you a right floating div where the text is in italic. The advantage is that you combine whichever of these basic classes you want. I’ve found this also helps me to keep my div structure clearer.

  49. Refik

    Jan 20, 16:34

    Nice article, I guess some of these tips will be very useful for my own web site! Thx

  50. Thame

    Jan 20, 21:50

    Thanks everyone,

    Barry: Yes, multiple classes can be very helpful and I’ve seen a technique at my job that uses this. When replacing text with images using the text-indent method, it can be helpful to create a “replaced” class that includes only the text-indent and a different class for the background image. This way, it is easier to see which headline is actually being replaced and which is simply being styled otherwise.

  51. Cheyne

    Jan 21, 04:28

    Great article, and some great suggestions from the comments. You have been blogged at www.thewebdesignblog.com

  52. Nina

    Jan 21, 19:31

    Awesome article. Will definitely keep these rules in mind for my next redesign.

  53. Thame

    Jan 22, 21:02

    Thanks to both of you.

  54. Rizky

    Jan 23, 00:59

    comments on tips #1 :
    too much indenting will definetely increase the file size. not a very good idea.

  55. George L Smyth

    Jan 23, 14:45

    Personally, I like to have the closing brace on its own line. There are two advantages. The first is that it more clearly defines the scope of the class. It is visually easier to see the opening and closing brace. The second is that it makes it easier to add a line. One does not need to find the closing brace, place the cursor, press Enter, then type in the new code, they can simply open a line above the closing brace and go.

    Bottom line is that one should use whatever they have a comfort with and works for them. By having ANY system in place, modification becomes much easier.

    Good article.

  56. Mark C

    Jan 25, 08:21

    “Combining properties onto a single line using shorthand properties means that your CSS will be easier to understand and edit.”

    Sorry, I don’t agree. Having each element defined spells it out, therefore easier to understand. Also what happens if I write this:
    border :1px solid #000066;

    then want to make the bottom margin black? I think that if you want more flexibility then write it out in full, it’s good practice and also makes it easier to understand for people learning the art.

  57. Ivan Minic

    Jan 27, 08:26

    Very good tips!

  58. Vincent J. Murphy

    Feb 16, 09:56

    And always remember to define the background-color of your pages. For example, this page needs a background-color: #fff;

  59. Vincent J. Murphy

    Feb 16, 09:58

    Hmm, or not. Still hard to read, though. :)

  60. Thame

    Feb 16, 11:49

    I didn’t set a body background color because if a user has gone through the trouble of defining a default color for their user stylesheet, they probably had a good reason for it.

    Also, I had a visitor contact me because they could not see the text because of their high-contrast scheme and my forced background color.

    Can you tell me what part is hard to read for you and what you’re running so that I can fix it?

  61. loans

    Dec 11, 02:41

    According to my own analysis, billions of people in the world get the personal loans at different banks. So, there’s great possibilities to find a consolidation loan in every country.

Comment

About & Contact

I am a seventeen year old freshman at the University at Buffalo majoring in Biomedical Sciences. If you have any questions about this website or would like to work with me on a web design project, feel free to contact me

Read More »

Flickr