CSS: How can I get rid of the default window "padding"? An element set to 100% width doesn't reach the window's borders

Alex picture Alex · Dec 31, 2010 · Viewed 74.3k times · Source

So I have an element that is placed directly inside body:

<body>
    <div id="header">Some stuff...</div>
    Other stuff...
</body>

The following is the CSS used:

body{
    text-align:center;
}
#header{
    margin:auto;
}

So the #header div is set to 100% width (default) and is centered. Problem is, there's a "space" between the window border and the #header element... Like:

|  |----header----|   |
^window border        ^window border

I tried adjusting it with javascript, and it successfully resizes the element to the exact window width, but it doesn't eliminate the "space":

$('#header').width($(window).width());

One solution seems to be to add the following CSS rules (and keep the javascript above):

#header{
    margin:auto;
    position:relative;
    top:-8px;
    left:-8px;
}

In my browser this "space" is 8px - but I'm not sure if that's the same across all browsers? I'm using Firefox on Ubuntu...

So what's the right way for getting rid of this space - and if it's what I used above, do all browsers act the same?

Answer

BoltClock picture BoltClock · Dec 31, 2010

body has default margins on all browsers, so all you need to do is shave them off:

body {
    margin: 0;
    text-align: center;
}

You can then remove the negative margins from #header.