How do I refactor my CSS? [duplicate] - css

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Manage CSS Explosion
I intended to build my web site with consistent styles and a coherent CSS scheme. But styles have crept out of control as I fine-tune individual pages (especially the main search form).
I've already gone through the process one time of breaking down the styles and rebuilding almost from scratch, and now it looks like time to do that again. How can I be efficient about this? I'm looking for a methodology, not a software utility (though I'm open to suggestions there...unless they cost money...).
Added note: I'm using a CSS framework and it's difficult to keep padding and margin coordinated.
Added note 2: The initial responses to this post are about best practices for CSS. Let's assume I already tried to follow best practices (in fact, I did). Now it's the clean-up procedure I'm looking for.
Added note 3: As of 14 June, combining this response (which I just found) with my post below is possibly a comprehensive answer.
Closure notes:
I learned my question is too general, and for that reason I wish I hadn't posted it. (Maybe that's why it got a down-vote ... I'll never know without a comment to explain the reason.) On the other hand I got just what I needed, so I'm happy I did post it.
I'm surprised I didn't get an up-vote for my answer -- even with the priceless input by others, I think it stands up pretty well.
My acceptance is going to be based largely on the usability of the answer, from my point of view -- a point of view that is sadly unable to digest some of the more exciting and comprehensive responses.
Closed as an Exact Duplicate
I just tried posting this again (subject, body, tags) to see if SO would suggest the post "How to Manage CSS Explosion". Interestingly, it did not. I added the tag refactoring to that post.

Split your css into separate files.
Put in one file the CSS reset (if you use one)
Then create a global.css file where you will put global styles that
apply to many-all pages
Then create individual files for your individual pages
Then start styling your pages. Every time you find a style rule that is reusable on many pages make it a CSS class and put it in the global.css file. Avoid using css ID's. You will find that you more often reuse things or will reuse in the future. In this case you use of course CSS classes.
Eventually you will find out that in your global.css you will find mostly CSS classes rules and html tag rules.
In your individual page CSS files you will find specific styles for each page.
That should give you a good first level of organization in your CSS. You can try to keep this separation through the whole development process, and for releases merge the CSS files into one and minify it.

my 2p worth about css cleanup, from a a previous similar question:
Tips for cleaning and maintaining a big css file
hope that this may help you together with others' answers!
start branching the project (here I suppose that you are using a version control tool) - that will allow you to play independently with the code and tag any milestone you will reach.
format your CSS with a beautifier - it will increase readability and will help searching for specific declarations without missing any instances.
try to identify unused / redundant css and get rid of it.
you could try to make your selectors shorter (e.g. .main .foo .bar might be fine as .bar) - it will improve readability and increase the performance, but take this with a pinch of salt and be ready to go back if things start to break at every step you take.
try to eliminate, if possible, any !important - make the selector more specific if needed. A css reset could help with that if most of the !important statements were made to fix browser-specific issues, otherwise introducing a css reset now could potentially add more problems than solve them - this, if there is no css reset in your app at all.
break and regroup the css into different modules (and files if that helps) - Object Oriented CSS is a possible technique to keep things more maintainable, it works best if you start with it but it may also help you in refactoring. https://github.com/stubbornella/oocss/wiki is a valid one but there are alternatives that you can consider, like SMACSS.
After that , you may consider using a css preprocessor such as Less or Sass, allowing you to define variables and mixins (similar to functions), modularity and much more - this may end up being a very expensive task though, so evaluate carefully if this will bring you more benefits than pain.
test as much and as often as you can, consider unit tests to make sure that any changes you make don't break anything somewhere else.
Sometimes re-writing everything may end to be less time consuming than refactoring, so don't be afraid to leave things as they are if your assessment will show that refactoring will not bring enough benefits.
EDIT
Things change and evolve for good; with regards to OOCSS/SMACSS approach, I have been happily following for a while, Yandex's BEM methodology for CSS, I would like to add it as an additional recommendation to the above

The first thing I'll do is separate the CSS based on the purpose. Maybe first the general page layout (DIVs, boxes, ...), then the styling (fonts, H1/H2/.../Hn titles), then some more specialized CSS (CSS for tables, for forms, for specific components of the site).
Such a separation helps to organize the changes; if you have to change or add a font, you know you'll find it in the styling section.
If you have to change the page layout, there goes the same, and so on.
Things tend to get messy when you have "individual pages"; is their layout so different?
You probably have to abstract the common features of the pages (for example, a main content container box) as long as you can.
Then think about specializing more the layout (1-column, 2-column) and so on.
If you have a programmer background, just think about classes and inheritance, the concept - yes I know it's a totally different domain... - but the concept can be useful in designing your css.

Based on this current round of work, here is what I've got so far:
the Planning
Have a system for handling To-Do notations in your HTML and CSS. Many IDEs support this directly, or a global search function will do just fine. Besides tagging issues, you want to note priority and perhaps even functional area (but keep it simple, not a burden).
Don't start revising your code. Use your To-Do system to plan first.
Make a concise list of your overall goals.
Consider overall sylistic changes such as color or font scheme.
Review best practices for CSS. Identify areas where your approach is ineffective, or where a good approach can be applied more consistently. Examples:
Consolidate classes
Eliminate haphazard use of in-line styles
Remove styles that are unused or redundant or conflicting
Improve general consistency; apply a set of conventions
Improve units of measure
Use class and id names that reflect content rather than format
Decide how much of the browser market you want to support and how much to embrace or rely on the newest standards.
Decide if there are any new approaches you want to adopt. Examples:
Use of a reset style sheet to standardize browser presentation
Use of a CSS framework
Use of a specialized library, for example to help with forms
Dynamic CSS (I recently followed advice to use PHP to handle my CSS, so I could dynamically control my color scheme. But I returned to straight CSS, because I like the presentation of CSS code in my IDE and the hybrid method messed that up.)
Review your list of goals and decide which should be pursued now. Any large-scale change should be treated as separate, if possible. If your column layout is a mess, it's not the time to learn how CSS can elegantly replace your javascript. The same goes for best practices, stylistic changes, etc.
If you have your CSS files configured for speed (for example, compacted footprint or all CSS in a single file), change that. Break the code into a human-managable format. Later when you're finished, try benchmarking to see if the more legible version is also efficient enough for production use.
Submit your CSS to a validator. Note any violations you want to fix.
Find instances of in-line styles in your HTML (search for the style attribute). Note any that should be moved to a style sheet.
the Work
Follow your To Do manager. Make common-sense back-ups. As you go, test your work on several browsers.
If you are into regular expressions, be warned: regex is often not effective or safe for rewriting CSS. (Not as hazardous as for HTML, but still). Regex may be useful sending CSS changes into the HTML, but again be careful.
If you have a lot of tweaks to margins and padding, try globally resetting all of them to 0px (okay, use regex here). Then systematically build them back up. You can resolve a lot of confusions this way. Of course, don't include any library or framework style sheets in this process.
Again, submit your CSS to a validator.

I see people has already suggested using approaches like OOCSS etc., so I'm going to offer a different/additional line of thought. I believe that the problem lie deeper than within your CSS and the way you write it. I believe the reason your CSS gets out of hand is this quote from your question:
... as I fine-tune individual pages ...
That makes me think that the problem much lie within your design, rather than you CSS, so let me elaborate a little bit on that. In my opinion a great design is a design that doesn't have to be customized for each individual page - and there are several reasons for that. The main reason is, as you've mentioned yourself, your CSS get out of control. Small tweaks and fixes on individual elements, depending on where they are placed, often leads to a mess that is a pain to maintain and work with. There is also a usability-reason in play here. I believe a UI becomes easier to use if the user is familiar with the UI and recognize herself from page to page, without to much variation. Of course you could have some element that isn't present on each page, or that vary somewhat between pages, but I always strive to keep them at a minimum.
My suggestion is therefor that if you intend to rewrite your CSS, which is time-consuming and hard work anyway, then why not go over and re-evaluate your design at the same time. You will probably find that there are elements that you can modify so that they look the same. Make it a goal to get rid of as many UI-elements as possible, without compromising the design. When you've unified the design as much as possible, then it is time to refactor your CSS, and maybe even your markup?
At this point, it might be better to get rid of all your CSS and start fresh. If you continue on your old code, it is easy to get lazy and get stuck with some of your old less efficient code.
For the coding, I believe the other answers contain lots of good recommendations and best practices. I would personally vote for OOCSS, a new discovery for myself as well, but it has improved the way I structure my CSS a lot. So have a look at that! That will also help you think in terms of reusing elements and the CSS for them, which goes a long way for simplyfing your CSS.

This answer is in regard to the note;
"I'm using a CSS framework and it's difficult to keep padding and margin coordinated." only.
Using a css pre-processor will solve this problem.
Because css has no way to assign inheritance and therefore we have to repeat 'margin:10px' over and over.
with a pre-processor you just do
#margin {10px}
#padding {10px}
then
.mySelector{
margin: #margin;
padding: #padding;
}
For the broader question rethink/simplify your design as your css is directly proportional to the complexity of the design and there is not much you can do about that.
See also, http://www.stubbornella.org/content/2011/04/28/our-best-practices-are-killing-us/

This is more advice about making your css maintainable than the Q of how to manage the process.
I create a bunch of separate css files each narrowly tailored to a specific attribute (colors, fonts, margins, corners) or feature (nav, form). Then I use a compile phase to combine and minify these files into one or more files to be sent to the client. I do this during my built/test process, but it could be done dynamically by a CGI script.
Before adopting a pre-compiler, consider the often-overlooked multiple-selector syntax:
element,
otherlement
{
margin:10px;
}
In this example, whenever I want an element to have a 10px margin, I add it to the list. I separate different sets of attributes this way - I may list the same element 5 times in my css - associating it with 5 different sets of attributes.
Also don't overlook adding various classes to the body tag to create OO-like inheritance - say you have 3 main sections of your site - assign the body tag a class based on those sections. Likewise, if you have 1000 product pages, you can give the body tag a class like "product485" and then create styles that apply just to that page. For example:
h1 {
margin: 10px;
}
.product485 h1,
.product484 h1
{
margin: 5px;
}
.contact h1 {
margin: 15px;
}
This might all be in a file called "margins.css" which specifies only margins.

Related

What is the best way to use CSS? (NOT *learn* but really *use*) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I know CSS and I'm learning more and more common pattern. However, I always feel like I'm hacking instead of doing it the right way.
For instance, some people I respect tell me that using css reset is unnecessary while others live for it. Also, there are so many great css framework (for grids, etc.) that even thought I understand them, I never really know when to use them.
So, basically, my question is: Once you understand how CSS work, is there a recognized "best" approach used by excellent web developer? As in python, one should try to use the common pattern and read PEP 8. Or, in C++, after understanding the syntax, reading the effective serie by Meyer is an excellent "second" read.
Sorry for taking that long to explain.. I just didn't want to have answer like: Read "Beginning CSS" which explain how to change the background or how to set font. I'm really looking for a good standard approach.
Should we use reset?
Should we use only one file per site? One for homepage and one for the rest? One basic file and once different for every big sections?
Is it bad to have a 2k+ css files? Does it mean it should have been refactored and that it contain to much duplicate?
Should I define parent at the top for normal font, color, h1, etc., and then, when it's different change it per sections.. or instead always use the standard one and redefine each and every section.
Should I use .class and #id a little bit everywhere, or should I try to minimize them and instead use long descriptor such as:
.content .main tr td span a
or
span.classname a
Thank you!
tl/dr:
What's the best "second" read once you already understand CSS but would like to use it in a clean/professional way?
[EDIT]
Thanks all for your answer. I know I asked quite a lot of questions.. but they were only examples for the real question which is: What is the best "second" read once you already understand CSS but would like to use it in a clean/professional way. I.e., I was hoping to read a book explaining the examples I proposed.. but also would explain lots of other things that aren't css-syntax but more css-best-professional-use.
People will have a range of answers for these questions, but here are the approaches I would take:
Resetting
If you're working on a fragile layout -- one that could easily break if a few pixels aren't where you expect them to be -- consider using a reset. I would look into normalize.css. Instead of completely overwriting browser defaults, it smooths out the differences between browsers.
You could also consider resetting specific elements if you find yourself adding a lot of margin: 0; to your stylesheets.
Splitting up CSS documents
Google recommends splitting them up so that individual pages aren't forcing users to download lots and lots of stylesheet rules that aren't actually used on the page that they're visiting.
Yahoo recommends combining files to minimize the number of HTTP requestion
Obviously, finding a balance is important, and this SO question weighs some of the pros and cons.
Classes and IDs or long chains of selectors?
I try to keep classes and IDs to a minimum (in both my HTML and my CSS). They tend to be more fragile when you're building pages that others will update with WYSIWYG editors. I add a few IDs or classes to large blocks of the page, then use CSS to target specific elements within those blocks. This is easier if you avoid deep nesting in your HTML as much as possible.
Working with a CSS preprocessor such as LESS or SASS can help you write more readable stylesheets. The ability to nest style rules in both LESS and SASS has helped me avoid a lot of specificity-related issues.
Still, specificity is a good CSS topic to be familiar with:
CSS-tricks has a good article covering specificity
The W3C's own documentation is worth reading.
Additional Resources
As far as additional reading is concerned...
SitePoint's collection of articles and tutorials on CSS is a great resource for more advanced CSS tutorials, and they also feature some good articles covering CSS issues that are more advanced than what you'd find in many beginner-level books.
Resets: I think yes, some dislike them, so it's up to you to figure out which one you like
Split vs. Unified files: Depends. There are advantages to both (chorus: advantages, advantages!) One CSS file is easier to browse, and you can clearly find relationships in a single file. Then again, if you have planned the structure of your site, are developing compartmentalized widgets, or have lots of people working on the CSS committing files, a decentralized method might benefit you. With multiple CSS files, you can always use a compressor to serve them to the client as a single file, so it's more of a maintenence question.
Large Files / Line Count: Are you saying you have 2,000 CSS files (holy crap!) or 2,000 line CSS files? Both aren't great, although the latter can be managed quite easily in an IDE that provides outlines and handles inheritance for you.The former...well, at least you have job security.
Parent Definitions: Again, no right answer. The CSS rules for a small site will vary greatly from an enterprise level site. A good starting point might be checking out how jQueryUI handles styles and then forming your own opinion from there.
Correct Selectors: Steve Souders talked about optimizing CSS selectors, coming to the conclusion that's it not worth it for your average site. So ignoring CSS optimization and based on your example, I'd say the second one is waaaay easier to maintain and ultimately far more predictable. If you HTML changes even slightly, the first one will break quickly. The second won't, and is far more portable.
There are things you can do in CSS to make your life easier. I highly recommend using a grid system for layout (blueprint, 960GS, etc). I personally like using a reset since it makes pixel perfect designs easier to manage. Other than that, research what people like Eric Meyers or site likes alistapart.com or smashingmagazine.com have to say on the topic.
tl;dr - there is no right answer, but definitely some good options
I can answer your questions based on my own experience, not necessarily the best practices out there.
I reset certain tags, but not all the tags like the "CSS purists" do. Keep in mind that if you are using certain CSS libraries, like JQuery UI, Superfish menu, etc.. resetting the tags can really mess up these libraries UIs.
I usually have one general layout/configuration CSS file and every complicated page has its own CSS file. So, every page includes these 2 CSS files plus my UI library files (JQuery UI, etc). This makes it easier for me to pin point and maintain it.
2K+?? Yes, very bad in fact. If you have file that big, you should really use YSlow to see how long it takes to load that file. The longer you page takes to load, the faster you users leave your webpage, unless they are forced to use it. :D
I always like to "scope" my CSS, by prefixing with say #app. This ensures my global setting only affects my page content and layout, and they do not override the UI libraries.
Use .class and #id in whatever way it makes sense to you. If you know this tag exists only one time, then use #id. If you know it might occur more than one time in the page, then the only option is to use .class.
As with many things there aren't really rights and wrongs, it's more about prefernce and manageability.
I use CSS Reset on some elements, I prefer the blank canvas start instead of finding a load of unknown defaults.
I don't think file size is really an issue, again what is easiest to manage is really more important. Split the file if it logical to do so.
Give some thought to optimisation and try to avoid unnecessary duplication. I like to define a parent font/styles as you call it for the most commonly used style, then just define the others as required.
Personally I like to define some common classes, i'm not sure if it's optimal but it's very usable, such as:
.bold {font-weight: bold}
.clear {clear: both}
.red {color: red}
If you do this for common requirements you can then simply use code like
<p class="bold red"></p>
<h2 class="red"></h2>
<br class="clear" />
Simples!
Use tabs. Makes it easier to see. Also i rather use .classname than #id. Example of a piece of css of one of my websites:
body {
font-family: Arial,Helvetica,sans-serif;
font-size: 11px;
background-color: #99D9EA;
}
.lcategorie {
background-image: url('http://images.alphenweer.nl/i/gradient-menu-left.png');
background-repeat: no-repeat;
padding-left: 2px;
text-align: left;
color: #FFFF00;
font-weight:bold;
width:200px;
height:20px;
display:block;
cursor:pointer;
}
.rcategorie {
background-image: url('http://images.alphenweer.nl/i/gradient-menu-right.png');
background-repeat: no-repeat;
padding-right: 2px;
text-align: right;
font-weight:bold;
color: #FFFF00;
width:200px;
height:20px;
display:block;
cursor:pointer
}
In addition to the good answers above, what you just described in your question is also otherwise called as Learning Curve.
We all go through it. It is inevitable, according to me.
The best approach probably is to make the best use of the vast resources available and then filter them out. Which is a knack developed only over time.
I don't think there are shortcuts. Although, I do agree, it would be nice to have a guiding hand to help us avoid pitfalls and time-wasters and tell us about all the best-practices.
But even those are available out there thanks to some really passionate, expert-in-their-field bloggers.
So explore-away is what I'd suggest.
If your lucky enough to have a Mac or a Hackintosh... then I highly recommend CSSEDIT (unfortunately only available on Macs). It will allow you to rapidly develop your understanding of CSS. I realize this doesn't answer your question, but if you try it, you'll understand why it is so important to the learning curve. Sadly, nothing else on windows comes close. I use windows 99% of the time and switch to my mac for CSSEDIT.

Is it always bad idea to use inline css for used-once property?

I have a table, with 10 columns. I want to control the width of each column.
Each column is unique, right now I create an external CSS style for each column:
div#my-page table#members th.name-col
{ width: 40px; }
I know there is a best practice to avoid inline style.
I do approve using external CSS for anything look'n'feel related: fonts, colors, images.
But is it really better to use external CSS in this case?
It does not incur extra maintenance cost.
It is easier to produce.
Cons I can think of:
If you have separate designers and development team - using inline styles will force designers to modify content-file (aspx in my case).
It might use more bandwidth.
Anything else I've missed?
IMPORTANT: I am asking about only one specific case where style used will ever apply to exactly one element, and is not part of the global-theme, such as width of one particular column.
There are lots of reasons why style="" is bad. I consider it a bug anywhere I encounter it in my codebase. Here are some reasons:
style= has higher priority than other CSS selectors making it hard to effect changes in the stylesheet; the stylesheet has to work harder to override these.
style= rules are hard to find in the code when you need to make global changes.
You download this CSS code with every page view.
If you have multiple stylesheets for the same HTML codebase your style= rules are not part of the stylesheet and thus are unchangeable.
However, if you are generating content and it's difficult to describe this content in a static CSS file, you might also need to generate the CSS to match that content. It is often easier to simply generate style= rules despite the drawbacks. If, however, your generated content can be easily described in a CSS file, because the generated structure doesn't often change, or because you can easily generate HTML AND a CSS file at the same time, then it's probably better to not use style=.
Some suggestions for alternatives to style= that may be appropriate:
Instead of inline styles, use class names. Works well if you have lots of columns in your table that have the same properties, and which you expect to always have the same properties. Then your stylesheet can remain fixed while your HTML is fluid, since the CSS only references classes. This is probably the approach I'd use.
Use JQuery or some other javascript library to style your objects programmatically after the page loads.
Easier to produce is not really a valid argument - people like splitting huge chunks of code into smaller chunks - same with code and markup.
However:
+ No extra HTTP connection (unless you are already downloading a .css file anyway)
- Every time the page gets sent, this CSS is sent with => more bandwith
- Designers need to modify CSS in Application Code (bad practice)
Usually, you shouldn't - unless it's a really well thought through performance tweak as google does.

Should I make my CSS easier to read or optimise the speed

As I was working on a small website, I decided to use the PageSpeed extension to check if their was some improvement I could do to make the site load faster. However I was quite surprise when it told me that my use of CSS selector was "inefficient". I was always told that you should keep the usage of the class attribute in the HTML to a minimum, but if I understand correctly what PageSpeed tell me, it's much more efficient for the browser to match directly against a class name. It make sense to me, but it also mean that I need to put more CSS classes in my HTML. It make my .css file harder to read.
I usually tend to mark my CSS like this :
#mainContent p.productDescription em.priceTag { ... }
Which make it easy to read : I know this will affect the main content and that it affect something in a paragraph tag (so I wont start to put all sort of layout code in it) that describe a product and its something that need emphasis. However it seem I should rewrite it as
.priceTag { ... }
Which remove all context information about the style. And if I want to use differently formatted price tag (for example, one in a list on the sidebar and one in a paragraph), I need to use something like that
.paragraphPriceTag { ... }
.listPriceTag { ... }
Which really annoy me since I seem to duplicate the semantic of the HTML in my classes. And that mean I can't put common style in an unqualified
.priceTag { ... }
and thus I need to replicate the style in both CSS rule, making it harder to make change. (Altough for that I could use multiple class selector, but IE6 dont support them)
I believe making code harder to read for the sake of speed has never been really considered a very good practice . Except where it is critical, of course. This is why people use PHP/Ruby/C# etc. instead of C/assembly to code their site. It's easier to write and debug. So I was wondering if I should stick with few CSS classes and complex selector or if I should go the optimisation route and remove my fancy CSS selectors for the sake of speed?
Does PageSpeed make over the top recommandation? On most modern computer, will it even make a difference?
should I make my CSS easier to read or optimise the speed?
You should do both.
You should write your CSS so it is readable and if you want to collapse it, use a tool that automates that to generate the "production CSS".
So you should be working with nice readable blocks and the published file should be tiny.
In terms of the specific selectors
#mainContent p.productDescription em.priceTag { ... }
Only adds value if you have
p.productDescription em.priceTag { ... }
Or
em.priceTag { ... }
In other places that you don't want to affect - for example if you had a "#secondaryContent p.productDescription em.priceTag" that you didn't want to apply the style to.
So if you want to use
em.priceTag
And have the rule applied to all, you'll actually see no performance issue (the difference would be about the same as the file-size difference you save anyhow by having less chars in the rule).
HOWEVER... don't pollute your HTML with tons of class="" attributes just because you don't want to write a proper rule.
I personally have found that the complex selectors are more confusing long term, just be sure to give the classes appropriate names.
Long selectors are going to have a performance impact as it requires walking of the DOM each and every time to analyze the process. The way I see it there are times and places for it, but it is an exception, not the standard rule.
Define you priorities.
Readability
Efficiency
Speed
Nowadays, except on a real specific projet and complex page, you don't need to obfuscate your code to speed it up.
First think to maintainability.
By the way, using #id is a good practice both for readability and speed, since it doesn't need to walk through all the DOM to find it. Same apply for you.

Managing CSS conflicts

So i am working with a few CSS developers and every now and then we run into layout issues which have been fixed previously because one of the css developer did something which conflicted with something else.
We are already using SVN .. each CSS guy has his own css file he works with. So my question is what steps should be taken to minimize:
1 : layout conflicts
2 : increasing re-usability of previously written styles.
3 : minimize wasted time trying to merge the styles together in the final css.
I would really appreciate any tips you guys have to offer.
Update:
I am not one of the CSS developer, i just take care of the backend stuff.. so please keep in mind that i am a total newbie when it comes to CSS norms.
Define a naming convention for your CSS files to prevent conflicts (prefix?)
Have an automated process that you can run before check-in (check-in tests) to see any potential conflicts
Discuss what you will add (code review?) and avoid the conflicts altogether
I dont know of any namespacing you can do to avoid CSS stylesheet name conflicts so, I suggest those. They are things that many large companies do already.
A good starting point is to disallow using general tags in specific css files. Each developer should only use classes and ids. All general tags should be included first on all pages, so that special tags may overwrite them later.
Changing the general tags should require more planning than changing each developer file.
With general tags I mean
div {
/* affects all divs */
}
and each developer should only do
div.something {
/* potentially overwrite defaults for div */
}
and the html file should be like
link href="general.css"
link href="dev1.css"
link href="dev2.css"
The best thing you can do is assign areas of responsibility - if you are all working in the same area of the site you are bound to have conflicting changes and will only create difficulties for yourselves because you will constantly be stepping on each other's toes.
Once you have established a common baseline for the styles of your site, divide the main areas of the site amongst you and only work in those areas. When changes need to be made to the baseline, make them out in the open and communicate with your teammates about this change so that no one is surprised.
I am not going to pretend that this is easy to do - working on something as a team is a challenge that the entire software development industry has yet to completely solve. Good luck!
All others have good answers, but I'll add this: Strongly encourage the use of IDs in selectors. ID-ing important elements generally pays off in the long run because it allows for better testability and less conflicts.
CSS Example:
#myid selector { ... }
#myotherid selector { ... }
General styles really should go in a top-level or general stylesheet that everyone manages, if possible.

Daunting task of refactoring 5000 line CSS. Any tips?

I've just been assigned the task to refactor a huge 5000 line CSS file... but here's the worst part - I also need to make it IE6 compatible. Any CSS gurus have suggestions of tools, or possibly tips (common pitfalls) for use in my monolithic expedition? Cheers.
checkout sass... it includes the ability to convert css to sass.
http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html
A sass file is a yaml file that can be parsed down into a css file. It allows you to use variables and alternate organization...
sass example:
!main_color = #00ff00
#main
:color = !main_color
:p
:background-color = !main_color
:color #000000
css output:
#main {
color: #00ff00; }
#main p {
background-color: #00ff00;
color: #000000; }
Some tips:
Use version control so you can roll back when needed.
Come up with a checklist of visual tests to run through after each change, in each browser. A spreadsheet of URL links and things to look for, building on them as you run across problems (think "unit tests" but not automated).
Use a CSS-specific beautifier first to get everything into the format you prefer for braces, etc.
Consider using something like SASS to "compile" your CSS as you go along.
Comment the heck out of things, especially where you're doing IE6-specific stuff.
Future-proof yourself by building a separate file with IE6-specific directives as you go along, or at least use Microsoft's way of filtering them out for other browsers.
Use the W3C Validation often.
Mechanically, I would attack it like this:
<link type="text/css" href="newhotness.css" />
<link type="text/css" href="newhotness-ie6.css" />
<link type="text/css" href="oldandbusted.css" />
Move code from the third (old) file into the other two, cleaning up as you go. That way you can validate your code without worrying about tons of errors in the old stuff, and you can track your progress, Ctrl-Tab between them more easily than between locations in a single file, etc.
(If you can't control the markup to add your CSS files, use an #import at the top of the old file.)
Start from scratch!
Assuming you can check all the major pages manually, I would be VERY tempted to wipe the entire file and start from scratch. Spot-checking for IE6 inconsistencies, you'll be doing nearly the same amount of work anyway, but it will be much, much more painful if you're modifying old, browser-specific CSS.
That 5000 lines may well be expressable in 2000 lines of modern, well-designed CSS. I think most experienced CSS developers would find it less work to write 2k lines of new CSS than modify 5k lines of horrible CSS.
http://www.codebeautifier.com/
which is based on this:
http://csstidy.sourceforge.net/
Not necessarily CSS, but here's worflow tip: use GIT.
start off by importing the files in git;
commit for every minor step, and record what you did;
whenever you find that you broke something, you can identify the exact same step broke using git bisect ( a good description );
For extra kicks, here's a talk about code coverage for CSS to help you quickly weed out unused rules.
As Triptych said, I would start from scratch. Also, consider the following:
use a CSS reset file to smooth out cross-browser inconsistencies: http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/
get it working perfectly in Firefox, then tweak for other browsers as needed
study the underlying HTML. How is it organized? Is it laid out with tables? all DIVs? Semantic tagging?
is the CSS used for layout or simply styling (fonts, colors, etc.)?
Once you get a feel for that, study the content. Categorize the layout and elements as much as possible, so that you identify all the common elements and can maximize the efficiency of your CSS
remember the C in CSS, Make the most commonly used font the body font, so that other elements will inherit it by default.
use relative units (ems) for font size, to allow proper scaling of text
try not to use ANY inline styles
make use of Firebug - it will let you inspect an element and see exactly what CSS is in effect and where the rules came from
don't be afraid to re-use portions of the old CSS, especially for things like dropdown menus, which can need very specific incantations to work properly
have fun! starting from scratch lets you implement best practices and learn a ton along the way. When you are done you are probably going to look back on this as a good experience.
there is a presentation here that should get you in the right headspace for tackling this task: CSS Systems
I would be tempted into creating a test suite first: automating page visits (perhaps with Selenium?), taking screenshots, then using something like ImageMagick to compare those with reference images.
Also, I second all the suggestions to use source control. If you later discover that your refactorings broke something that wasn't checked by the test suite, you can add a new test and then bisect your history to find the change that broke it. Git is good for that.
Get a code editor with good syntax highlighting. Also, goodluck I dont envy you.
My initial thought was does some like NCover exist for CSS, as it would be handy to see if all of the CSS is referenced. A quick Google on CSS code coverage found a few things- you might want to look yourself though: http://development.lombardi.com/?p=436
Install sass, run css2sass on your 5000 lines of css, proceed. After you are done with your sass file refactoring, run sass2css to regenerate the css file. Best of luck!
I'd suggest Stylizer - it is a CSS editor with an embedded live preview browser. It makes life much easier when editing CSS files and can tell you which rules affect which element on the page and more.
All of you guys saying he should start from scratch are wrong. You shouldn't. Try to identify the different parts the site uses. Put them on a sheet of paper. Find the parts that match together. Build a structure. Find parts of the application that are the same but are still styled with different rules.
Take that one part and name it. Then match all app parts that use that "pattern" with the correct HTML/CSS.
Repeat until you're done. Break up the large task in small chunks.
Identify whether the original CSS writer used standard methods like using a CSS reset. If he didn't, and everything is defined by #id without reusable classes, well, then maybe the guys saying you should start from scratch are in fact right. But my point here is that you can't just recommend that without assessing the situation.
Using the Dust-Me Selectors Firefox Plugin can be handy. It's a bit like a code coverage tool for CSS.
Tool suggestion: ReSharper by JetBrains. It will autocomplete CSS and rename selectors site wide from the CSS file editing window.

Resources