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

荒凉一梦 提交于 2019-11-29 05:17:33

问题


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?


回答1:


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.




回答2:


An easy way to solve this problem is by getting rid of all the margins. And you can do that by the following code:

* {
    margin:0;
}

This will solve the problem and will give you finer control over the margins of all elements.




回答3:


Add these to the style tag in body, like the following one:

body { margin:0px; padding:0px; }

It worked for me. Good luck!!




回答4:


I found this problem continued even when setting the BODY MARGIN to zero.

However it turns out there is an easy fix. All you need to do is give your HEADER tag a 1px border, aswell as setting the BODY MARGIN to zero, as shown below.

body { margin:0px; }

header { border:1px black solid; }

Not sure why this works, but I use Chrome browser. Obviously you can also change the colour of the border to match your header colour.



来源:https://stackoverflow.com/questions/4570212/css-how-can-i-get-rid-of-the-default-window-padding-an-element-set-to-100-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!