Tuesday, September 14, 2010

List margins and padding

Browsers don’t seem to be able to agree on how much padding and margin to place
around lists by default, and also how margin and padding settings affect lists in general.
This can be frustrating when developing websites that rely on lists and pixel-perfect element
placement. By creating a list and using CSS to apply a background color to the list
and a different color to list items, and then removing the page’s padding and margins, you
can observe how each browser creates lists and indents the bullet points and content.
In Gecko browsers (e.g., Mozilla Firefox), Opera, and Safari, the list background color is
displayed behind the bullet points, which suggests that those browsers place bullet points
within the list’s left-hand padding (because backgrounds extend into an element’s
padding). Internet Explorer shows no background color there, suggesting it places bullet
points within the list’s left-hand margin.
This is confirmed if you set the margin property to 0 for a ul selector in CSS. The list is
unaffected in all browsers but Internet Explorer, in which the bullets abut the left edge of
the web browser window. Conversely, setting padding to 0 makes the same thing happen
in Gecko browsers, Safari, and Opera.
To get all browsers on a level playing field, you must remove margins and padding, which,
as mentioned previously in this book, is done in CSS by way of the universal selector:
* {
margin: 0;
padding: 0;
}
With this in place, all browsers render lists in the same way, and you can set specific values
as appropriate. For example, bring back the bullet points (which may be at least partially
hidden if margins and padding are both zeroed) by setting either the margin-left or
padding-left value to 1.5em (i.e., set margin: 0 0 0 1.5em or padding: 0 0 0 1.5em).
The difference is that if you set padding-left, any background applied to the list willappear behind the bullet points, but if you set margin-left, it won’t. Note that 1.5em is a
big enough value to enable the bullet points to display (in fact, lower values are usually
sufficient, too—although take care not to set values too low, or the bullets will be
clipped); setting a higher value places more space to the left of the bullet points.

No comments:

Post a Comment