CSS:如何摆脱默认窗口“填充”?设置为 100% 宽度的元素不会到达窗口边框
所以我有一个直接放置在 body 内部的元素:
<body>
<div id="header">Some stuff...</div>
Other stuff...
</body>
以下是使用的 CSS:
body{
text-align:center;
}
#header{
margin:auto;
}
因此 #header div 设置为 100% 宽度(默认)并居中。问题是,窗口边框和 #header 元素之间有一个“空间”...比如:
| |----header----| |
^window border ^window border
我尝试用 javascript 调整它,它成功地将元素大小调整为精确的窗口宽度,但它并没有消除“空间” ":
$('#header').width($(window).width());
一种解决方案似乎是添加以下 CSS 规则(并保留上面的 javascript):
#header{
margin:auto;
position:relative;
top:-8px;
left:-8px;
}
在我的浏览器中,这个“空间”是 8px - 但我不确定这在所有浏览器中是否都相同?我在 Ubuntu 上使用 Firefox...
那么摆脱这个空间的正确方法是什么 - 如果这是我上面使用的,所有浏览器的行为都一样吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
body
在所有浏览器上都有默认边距,因此您所需要做的就是将其去掉:然后您可以从
#header
中删除负边距。body
has default margins on all browsers, so all you need to do is shave them off:You can then remove the negative margins from
#header
.解决这个问题的一个简单方法是去掉所有边距。您可以通过以下代码来做到这一点:
这将解决问题并使您可以更好地控制所有元素的边距。
An easy way to solve this problem is by getting rid of all the margins. And you can do that by the following code:
This will solve the problem and will give you finer control over the margins of all elements.
将这些添加到
body
中的style
标记中,如下所示:它对我有用。祝你好运!!
Add these to the
style
tag inbody
, like the following one:It worked for me. Good luck!!
我发现即使将 BODY MARGIN 设置为零,这个问题仍然存在。
然而事实证明有一个简单的解决办法。您需要做的就是为您的 HEADER 标签提供 1px 边框,并将 BODY MARGIN 设置为零,如下所示。
不知道为什么会这样,但我使用 Chrome 浏览器。显然,您还可以更改边框的颜色以匹配标题颜色。
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.
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.