Clagnut

Menu

Resetting default padding and margin

§ CSS techniques

A simple CSS rule appeared recently on the WSG list, generating a fair bit of discussion:

* {
   padding:0;
   margin:0;
}

Highlighted by Andrew Krespanis in his wicked worn blog, this little rule removes all the padding and margins from every element in your page. As you can see from Andrew’s test page, this is a pretty drastic rule so why on Earth would you want to use it? Two reasons: easier debugging and cross browser compatibility.

Many styling inconsistencies occur between browsers because browsers apply their own internal style sheet to HTML elements. These style sheets are very similar, but crucially they do differ. The most notable difference occurs with lists: Safari and Gecko-based browsers (such as Firefox) use padding-left to indent lists; Internet Explorer uses margin-left. Neither are right or wrong, they are just different. Because of this I’m forever making Ie behave like the others by using a rule like:

ul {
    padding-left:1em;
    margin-left:0;
}

There are plenty of similar rules I find I’m applying in every style sheet: removing all padding and margin from the body, un-indenting definition lists and blockquotes, removing bottom margins from headings, removing top margins from paragraphs. By using the global reset rule I can deal with all of these in one go and just apply padding and margins how and where I actually need them.

At first glance it may seem the global reset method requires you to subsequently style the margins and padding of each HTML element that you intend to use. resulting in verbose and wasteful code. However you can zero margins and padding in the one rule set and then set all block level items with margins in a second rule set, resulting in identical rendering across all browsers:

h1, h2, h3, h4, h5, h6, p, blockquote,
 form, label, ul, ol, dl, fieldset, address {
    margin-bottom: 1em;
}

I’ll certainly be using the global reset as the first rule in all my future style sheets. As an aside, Eric Meyer has been investigating removing all default styling (not just padding and margin). His conclusion is an eye-opener.