views:

2869

answers:

22

This may seem like a strange question...but here goes:

I'm currently working on creating a fairly large site using table-less design/css (obviously the best way to go). Unfortunately, I have a requirement that is completely out of my control that states I must have only one stylesheet for the site.

In some regards this is better because it forces me to think about style re-use pro-actively while designed the pages. On the other hand...the stylesheet is becoming monolithic and I'm quickly losing myself trying to find styles I know I've already defined.

I'd like to do myself (and anybody who has to work on the site in the future) a favor and make the CSS as readable and easy to update as possible. That's where you come in. I'm looking for formatting/organizational suggestions/best practices.

Somebody out there has to be better at it than I am.

+4  A: 

My site has a global.css which imports the other CSS in the order that they need to cascade.

example:

Global.cs file:
@import url('Directory/MainLayout.css');
@import url('Directory/Links.css')
@import url('Directory/Tables.css')

Doing it like this will help you organize your CSS.

Jason Heine
Keep in mind that "imports" are blocking: you'll see a bit of slowdown. If you can, try to keep stylesheets separate and use link tags or - better yet - concatenate them while serving them to the user. That said, if I can't concatenate I always use the above method.
ajm
@import slows down page download and rendering speed. You're better off using multiple <link> elements instead. http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
tj111
This may not work with his requirement. If he can only HOST one for example, this won't work. If his client doesn't want the client to download more than one file, it doesn't work either. In fact, if there is any non-arbitrary reason behind the requirement, this probably doesn't actually meet it.
TM
Doesn't that bypass his requirement for one stylesheet?
Matt Spradley
Yes you are right, this will cause a bit of a slow down. I think in today's world though, how much of a slow down do we really see?
Jason Heine
While depending on the user's connection the performance hit is minimal from my experience. I use Jason's suggestion almost exclusively now and have tested with various connections from dialups on up. The managability with this method is nice.
David Yancey
A: 

The idea of "Modular CSS" as described here http://24ways.org/2008/making-modular-layout-systems helped me organise my CSS well.

The cost is having multiple classes on html elements but that is what they are for.

edeverett
+27  A: 

I've recently switched to using code indentation to format all my stylesheets. It gets rid of the wall-o-text that most CSS currently resembles and makes browsing for specific statements pretty easy.

#menu {
  asd:asda;
}
  #menu a {
    asda:asd;
  }

  #menu ul {
    asd:asda;
  }
    #menu ul li {
      qwe:qwerty;
    }

#content {
  asd:asdf;
}
/* etc...*/
tj111
+1 for a great idea, I've never seen this done before! The only concern I would have is the fear of my IDE auto-reformatting my indentions, of course those settings can be turned off.
Joshua Poehls
I was thinking it would be cool if the IDE /enforced/ the indentation. :-)
Patrick McElhaney
this Helps for readability and definetly suggest indentation for that reason. However for lage stylesheets I recomend breaking the styles up based upon a usage / cascading organization.
David Yancey
Yep, this a great way to keep things readable. It also helps you to see the relationships between parent Elements and their children.
ajm
Yea, use it like python to "easily" see relationships and how things cascade. It's a nice technique.
Will Hartung
While formatting is great, what are you going to do when you have 1000's of lines of CSS. Formatting does not help when you have to scroll through lots of lines of code. Breaking it out helps you have a better organized structure which you can easily find what you are looking for.
Jason Heine
I'm not advocating putting all his styles in one file, just suggesting a way to format them.
tj111
@tj111 fair enough :)
Jason Heine
Great idea. This works best with an editor that does code folding based on indentation.
SorinV
I used to like indenting my code like this, but abandoned the practice as it was (in my opinion) more trouble than it was worth, especially if the rest of the CSS document is already well formatted.
Andy Ford
Very nice, but potentially problematic if you have something like #section1 ul,#section2 ul,#section3 ul {...}and then different formatting for different children.
Nils Weinander
Something collapsible will be of great use in conjunction with the indentation
Ismail
+3  A: 

You may find the Compass stylesheet framework useful. In Compass you can use Blueprint CSS, The Yahoo! User Interface Library or 960 Grid System.

Alan Haggai Alavi
I've been experimenting with compass/sass for a few weeks now, and I'm delighted. I makes it very easy to structure you css into separate files, use indentations to structure nesting and use mixins and variables to get consistency in your code. The screencast is worth a watch http://wiki.github.com/chriseppstein/compass
Tomsky
+28  A: 

Why not have multiple stylesheets on your development boxes, but have them merged into one in your deploy scripts.

Hexxagonal
This has the benefit making the end-user only making one request combined with the benefits of multiple files. You can also minify the result while you're at it, making the user experience even faster!
James A. Rosen
^ this1) use multiple stylesheets in development2) have script to merge and minify all style sheets into 1 small compact stylesheet3) profit
resopollution
@resopollution - um, you can't presume to know step two if step three results in profit. also, step one should be "underpants"
Jason
This runs the risk of having your CSS break when going from development to production.
Derek Adair
+1  A: 

If you're using Visual Studio 2008, the size and organization of your CSS files may not really matter. There's some tools built in that make styles SUPER manageable, even going so far as to give you a visual representation of each style for reference.

Scott Guthrie has a great blog post on this.

http://weblogs.asp.net/scottgu/archive/2007/07/25/vs-2008-web-designer-and-css-support.aspx

Jeff Blankenburg
A: 

I like to keep all my stylesheets (relatively) small and broken out by section (about, products, contact, etc.).

When pushing to production, I run front-end blender to consolidate and minifiy all of the stylesheets into a single global.css file.

This minimizes the overall number of CSS calls in the production environment (1 instead of 20!), avoids the overhead of @import, and allows for better caching/cache-busting as needed.

Mark Hurd
+7  A: 

Be careful using @import -- especially in a master css file. The @import stylesheets will not download in parallel and you cannot control the order in which they are imported (in IE). See the High Performance Web site blog for more information.

I organize my CSS file by putting the common elements (header, navigation) at the top and the more page specific elements at the bottom. It's not hard to find stuff because I usually debug/work in firebug which gives the line number of the element you are inspecting.

Emily
A: 

Great advice in all the responses above!

I always find myself doing the following:

  • Ordering my selectors in order from generic Element (h1, em, a) selectors to more specific selectors (div#foo, a#bar) and winding up with generic (div.blah span.biz) at the end. No real reason other than I know that, after Elements, it follows along in decreasing specificity.
  • Ordering attributes in alphabetical order within selectors. I've tried grouping them in meaningful ways (like position, left, and top always showing up together), but you'll find that things end up hard to read if attributes are missing. Alphabetical order is always nice and easy to skim. Example at the bottom as the editor's eating my code formatting.

  • Finally, I always make sure to comment anything that's tricky. For example, I had a background image that was a 4x4 dot that I repeated and used as a horizontal rule. As it repeated as a 4x4 block, I made sure to comment that so any other developers would see just what the heck it was doing and why I used so many 4- and 2- based values for sizing that Element.

Just remember: someone else is going to be looking over this someday, so make it easy to read and skim!

Here's how my selectors generally look:

div{ 
   float:left; 
   margin:0 0 0 1em; 
   padding:0 1em; 
   position:relative; 
   z-index:999     
}
ajm
+1  A: 

I put all my selectors on one line, with alphabetical attributes (like ajm):

#aside{ float:left; margin:0 0 0 1em; padding:0 1em; position:relative; z-index:999; }

I used to indent (like tj111), but since I use multiple editors on multiple platforms, the spacing quickly got out of whack, and I spent too much time fixing it.

The CSS file is ordered by major blocks: reset, typography and layout. Selectors are ordered by, roughly, their place in the HTML structure. Sprinkled throughout, I'll use "flags" so I can find major blocks of styles in a search:

/* =Header
Other comments can go here, too */
#header { key: value; nkey: value; }
#header h1 { key: value; }
Michael Hessling
Putting all your rules on a single line wreaks havoc when it comes time to diff the file; you can see that a rule for a selector changed, but you can't necessarily see which rule without examining it closely. Keep rules and selectors on individual lines, and let a tool like YUI compressor do the minifying.
rmurphey
I personally find it pretty unreadable as well. What’s the thinking behind it?
Paul D. Waite
A: 

Here's how I do it:

#container {
    font-size: 220%;
    margin-top: 15%;
    min-width: 600px;
    text-align: center; }

    #container p {
        font-size: 100%;
        line-height: 1.2em;
        margin-bottom: 15px; }

        #container .accepting { font-size: 16px; }

        #container .domain { font-weight: bold; }

        #container .smaller { font-size: 65%; }

        #container #ad {
            margin-top: 2em;
            margin:0; }

            #container #ad img {
                border: 1px solid #CCC;
                padding: 3px; }

I keep the selectors one line long if there is 2 or less settings in it.

Also use comments to seperate the sections, such as /* header */ & /* main */.

Edit: Take a look at minify for combining & compressing css (and js if you wish).

Sam
This is actually the way I've been doing things. I'm quickly realizing that the downside of this method shows itself when your stylesheet gets lengthy. Indentation starts to lose its meaning and you really can't see the commented sections.
Justin Niessner
Yea I'd have to agree with you, starting to find that on a recent project. I'm sure there are much better formats that scale, but for ease of use on the average site this works just fine :D
Sam
+1  A: 

I use http://styleneat.com/ to consolidate all my .css into one nice and neat file.

d.

dengel
A: 

first i work on how i'd like the general page elements to look, for instance my p, a, h1, etc tags at the top.

then i work on on section of code at a time, like #header for instance, and include everything relevant to the #header element. i separate sections with a comment, for instance:

/*---------------------HEADER----------------*/

so that it's nice and big when i'm looking for it later. i then create generic reusable classes near the bottom, like .disclaimer or something that can be put in a random p tag.

of course it's not so great if you want to keep file size down, but i find that a couple extra bytes in your css file to prevent you from going crazy when trying to find things later is absolutely worth it.

of course you can also minify :)

Jason
+1  A: 

Download and read Natalie Downe's PDF CSS Systems. (The PDF includes tons of notes not in the slides, so read the PDF!). Take note of her suggestions for organization.

If on a Mac, Use CSSEdit

Organize the properties within each selector block. Many people suggest alphabetization. Here's my approach. Pick the one that feels right to you.

Make sure you're taking advantage of CSS shorthand as much as reasonably possible. (remember that 'line-height' is unitless, so 'line-height: 1.5;' is the same as 'line-height: 1.5em;'... Also a unit does not need to be specified for zero values, so 'padding: 0px 0px 1em;' can be written as 'padding: 0 0 1em;'... the 'background' shorthand property defaults to a 'background-color' of 'transparent', a 'background-repeat' of 'no-repeat' and a 'background-position' of '0 0' so sometimes you can skip setting some or all these depending on the situation ... 'normal' and 'bold' font-weights can be written as '400' and '700' respectively). These may seem quite minor, but in a huge CSS file, they can add up and they're good habits to develop anyway.

As others have mentioned, use server side scripting if possible to minify your css file before serving it up to browsers so you can maintain a human-readable version.

Andy Ford
+1  A: 

Here's how I do it:


/* HEADER ------------------------------------------------- */

#screen-reader {position: absolute; left: -99999px; top: -99999px;}
#header        {background: url(../images/header-bg.jpg) no-repeat; width: 960px; height: 209px;}

/* NAVIGATION ------------------------------------------------- */

#main-nav      {float: right; margin: -194px 110px 0 0;}

I break up my CSS into sections with comments and make sure everything is in line. I just think it's a cleaner approach.

Nick Satkovich
+1 for good idea
metal-gear-solid
A: 

Using something like minify can work wonders. You can have several stylesheets that upon delivery, merges all into one http request. It also removes any whitespace from the Css allowing it to load faster.

In regards to managing a huge file, you might refer to alistapart's article on separating structure, type and color. With clearly defined comments to separate these sections of css, you'll find it much simpler to refer back and edit.

My preference is to separate all base HTML styles into one clearly defined (through comments) area of the style sheet. From there I have a structure section where all containers are defined. After that I separate using comments based on any unique templates. And sometimes I even separate any link styles on their own.

Hope that helps!

A: 

Here is one useful link from CSS Tricks

vladocar
+1  A: 

When a stylesheet gets really long I tend to favor readability of selectors much higher than the properties themselves. An example was given above where a whole rule is compressed on to one line. That is my default format no matter how many properties:

#container {width: 900px; margin: 0 auto; font-size: 1.2em; }

#header {width: 100%; }
#header .nav {margin: 0; }
#header .nav li {list-style-type: none; }
#header .nav li a {font-size: 1.4em; color: #0f0; }
#header .nav li a:hover {color: #3f3; text-decoration: underline; }

I'm not a huge fan of indenting, but it may help you visualize your HTML within the stylesheet. Either way you have a compact, scannable CSS file.

As for long sets of properties, I try to organize them so I can skip to the end or middle if I know what I'm wanting to tweak. Generally, put display/position/z-index first, then width/height/margin/border/padding/background, then any typographic properties like font-size or color, and finally throw all the browser-specific tweaks at the very end (-moz-box-shadow).

Chris Ruppel
readability of selectors is the up most impotent thing of css!
vsync
A: 

Make the most of inheritance, write scalable, reusable code and stack classes where appropriate.

I use a similar format to Nick Satkovich up there ^ and rarely feel the need to use more than one stylesheet.

I find that css indentation makes code less readable than an inline format. Well structured stylesheets with well named ID's and classes shouldn't need indentation.

Phil
+1  A: 

What @tj111 mentioned above, can be achieved using an online tool - styleneat.com. Works quite well for organizing huge stylesheet(s) without breaking anything.

Nimbuz
A: 

Perhaps you can use the alphabetising features offered here, for making each css file's elements easier to reference by eye.

LonnieBest