Content margins and padding in CSS

Page margins and padding are easy to define using CSS. By setting these values once in an external file, you can update settings site-wide by uploading an amended style sheet rather than every single page on your site that has an amended body tag.

Furthermore, in terms of page weight, CSS is more efficient. If using old methods, to cater for all browsers, you set the following body attributes:
<body marginwidth=”0″ marginheight=”0″ topmargin=”0″ leftmargin=”0″ bottommargin=”0″ rightmargin=”0″>
The equivalent in CSS is the following:
body {
margin: 0;
padding: 0;
}

If a CSS setting is 0, there’s no need to state a unit such as px or em.

The reason both margin and padding are set to 0 is because some browsers define a default padding value. Therefore, even if you set all body margins to 0, there would still be a gap around your page content. Setting both the margin and padding to 0 in the body rule ensures that all browsers display your content with no gaps around it.

Zeroing margins and padding on all elements

Although the previous block of code is clean and efficient, it isn’t something I use in my websites. The reason for this is that browsers place default (and sometimes varying) margins around various elements other than the page’s body, too. Therefore, my CSS boilerplates always include the following:
* {
margin: 0;
padding: 0;
}
The selector, *, is the universal selector, and the declaration therefore applies to all elements on the web page. In other words, add this rule to your CSS, and all default margins and padding for all elements are removed, enabling you to start from scratch in all browsers and define explicit values for those elements that need them.

  • Share/Bookmark

Related posts:

  1. List margins and padding Browsers don’t seem to be able to agree on how...
  2. Working with CSS shorthand for boxes This is something that is useful to get to grips...
  3. Web page backgrounds in CSS Backgrounds are added to web page elements using a number...

Related posts brought to you by Yet Another Related Posts Plugin.

Filed Under: CSS Basic

About the Author: I am designer and want to learn CSS

RSSComments (0)

Trackback URL

Leave a Reply

You must be logged in to post a comment.