In one of my Web Development classes we where asked to create a script that detects NE4,NE6+,IE4,IE6+ Browsers that display a compatable CSS script for each browser.
The best way is to avoid using browser dependent code as much as possible, but where absolutely necessary, use code that has been proven correct written by people who know a lot more than you and I. I would suggest JQuery, as that's my library of choice, but there are plenty of others out there (YUI is popular, as is Scriptilicious, etc). Google JQuery to get started. Also, google 'John Resig at Google' to see if you can find a talk he did where he discusses some of the techniques he uses to detect browser capabilities. It's very clever, as it adapts as browsers fix their legacy issues.
I built a simple Firefox Mac User Agent Detect that writes specific CSS. http://www.combsconsulting.com/code-firefox-mac-hack.html