CSS:如何摆脱默认窗口“填充"?设置为100%宽度的元素不会到达窗口的边界 [英] CSS: How can I get rid of the default window "padding"? An element set to 100% width doesn't reach the window's borders
问题描述
所以我有一个直接放在体内的元素:
So I have an element that is placed directly inside body:
<body>
<div id="header">Some stuff...</div>
Other stuff...
</body>
以下是使用的CSS:
body{
text-align:center;
}
#header{
margin:auto;
}
因此#header div设置为100%宽度(默认)并居中.问题是,在窗口边框和#header元素之间存在一个空格" ...
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
我尝试使用javascript对其进行调整,它成功将元素的大小调整为确切的窗口宽度,但并没有消除空格":
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());
一种解决方案似乎是添加以下CSS规则(并保留上面的javascript):
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;
}
在我的浏览器中,这个空格"是8px-但是我不确定在所有浏览器中是否都一样?我在Ubuntu上使用Firefox ...
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?
推荐答案
body
在所有浏览器中均具有默认边距,因此您要做的就是将它们削掉:
body
has default margins on all browsers, so all you need to do is shave them off:
body {
margin: 0;
text-align: center;
}
然后您可以从#header
中删除负边距.
You can then remove the negative margins from #header
.
这篇关于CSS:如何摆脱默认窗口“填充"?设置为100%宽度的元素不会到达窗口的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!