CSS未知的边距/填充出现

3

我的头部导航ID标签之间似乎有未知的边距或填充。

以下是div标签:

<div id="container">

     <div id="header">
          <p align="center">HEADER</p>
     </div>

     <div id="navi">
          <p align="center">NAVIGATION</p>
     </div>

</div>

与此相关的样式表如下所示:
#container
{
    width: 800px;
    background-color: #AFAF97;
    margin: 0px auto;
}

#header
{
    height: 75px;
    width: 100%;
    background-color: #888888;
}

#navi
{
    height: 50px;
    width: 100%;
    background-color: #aaaaaa;
    /*margin-top: -16px;*/
}

这是未知边距/填充的截图。 http://imgur.com/l37DVFc 另一种解决方法是设置负的margin-top值。但是为什么会有这个问题,以及它是如何出现的呢?

它来自于<p>标签。 - Ruddy
4个回答

4

始终使用重置样式

* {
    margin: 0;
    padding: 0;
}

使用CSS Reset,CSS作者可以强制每个浏览器将其所有样式重置为null,从而尽可能避免跨浏览器差异。

更高级的CSS重置。

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

固定:演示


3

就像我在评论中说的那样,它是来自于你的<p>标签。以下方法可以解决它。

你可以这样消除它:

#container p {
    margin: 0;
}

DEMO HERE


搞定了。但是为什么 <p> 会添加那个边距呢?正如你所看到的,HEADER、LEFT 和 RIGHT 没有那个 <p> 边距。 - user2902009
如果你仔细看,标题确实有一个来自'<p>'标签的边距,它是margin-top。如果你在容器周围加上边框,你会看到两者都有边距顶部。 - Ruddy
@user2902009 你可以尝试使用它们,但我不认为它们会起作用,因为<p>标签的工作方式不同。浏览器会自动在每个<p>元素之前和之后添加一些空间(边距)。 - Ruddy
大多数元素(DIV、B等)默认情况下(称为“用户代理”)其MARGIN和PADDING设置为零。然而,P默认情况下顶部和底部有1em的MARGIN(左右为零)。这就是为什么大多数网页在其CSS顶部都有一行很长的语句:“....,P,... {MARGIN: 0; PADDING: 0}”。 如果您这样做,您将避免此页面上的特定问题。 - Michel Merlin
要查看它,只需打开Chrome Dev工具并指向P:«用户代理样式表 p { 显示:块; -webkit-margin-before:1em; -webkit-margin-after:1em; -webkit-margin-start:0px; -webkit-margin-end:0px; }» - Michel Merlin
显示剩余2条评论

1
获取CSS。
* {
    margin:0;
    padding:0;
}

0

像这样

演示

CSS

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接