A beginner's guide to CSS hack avoidance

Whilst working on some CSS designs recently I realised that by zeroing the padding and margin of various elements in I was avoiding my pages having major differences when viewed in different browsers. Often these differences in rendering are caused by the default styles applied to pages by the browser. It's these styles that come into play whenever you view a page without a stylesheet.

Once you learn how to use CSS hacks if you are at all inclined to be lazy you might find yourself utilising CSS hacks even when there's no real need. So before you use that hack you must ask yourself the question is there an easier way?

To illustrate the point I knocked up a quick page to test out the theory that all browsers are different before you even start to apply CSS rules. In addition here is an screenshot to show the difference side-by-side for IE 6.0, Firefox, and Opera 8.0.

As you can clearly see there's a need to reset the styles so that when you apply your stylesheet all browsers are starting from the same place. One way to do this would be to use global rules on all of the tags that you are going to use. Like so:


  p, h1, h2, h3, h4, h5, h6, ul, ol, fieldset, form {
      margin  : 0; 
      padding : 0;
  }

In doing this you will have to then specify the paddings and margins on each element that you are styling manually. Which is no big deal, however, you could specify a global rule including your own defaults and work forward from that:


  p, h1, h2, h3, h4, h5, h6, ul, ol, fieldset, form {
      margin  : 1em 0 0 0; 
      padding : 0;
  }

Alternatively for browsers that understand it you could create a global rule for all elements like so:


*  {
      margin  : 0; 
      padding : 0;
  }

Thus saving you from having to add each element separately. See the links below for more on this method.

Now before anyone comments that I haven't followed this advice completely myself, well that's true but I've only implemented this where I thought it most important, how far you go with this is entirely up to you!

Now before I posted this article I did a quick google to see if anyone's been here before I have, and there are a couple of articles that touch on the same area, so kudos goes to them for their endeavours.