2

我在 div 块之间的空格方面遇到了困难:

<div id="maincontentwrapper" >
  <img src="images/content-top.png" alt="main content border image" border="1" />
  <div id="maincontent" >
    <div id="pagecontent">
       <h1>Mission Statement</h1>
    </div>
  </div>
  <img src="images/content-bottom.png" alt="main content border image" />
</div> 

这是创建一个带有完整边框图像的页面。一切都很好,但是只要我在页面内容中输入块级元素,例如所示的标题,那么 content-top.png 图像和 maincontent div 之间就会出现一个间隙。

如果我将第一个字符更改为内联字符,例如不间断空格或只是一个字母,则不会出现间隙。

这是(相关的)CSS:

img {
 margin: 0;
 padding: 0;
}
#maincontentwrapper { 
}
#maincontent {
 background-image: url('../../images/content-main.png');
 background-repeat: repeat-y;
 min-height: 300px;
 width: 757px;
}
#pagecontent {
 width: 625px;
 margin-left: auto;
 margin-right: auto;
}

谢谢你的帮助

4

5 回答 5

3

这可能是浏览器默认应用的边距。试试你的代码

h1 { margin: 0; }

添加到CSS。这有帮助吗?

(该h1元素不是唯一一个“遭受”此问题的块级元素,p在大多数浏览器中也具有默认边距。)

如果你很确定你的客户端的浏览器会支持 CSS3,你有一个备份机制,或者你不在乎,你可以做

.maincontent :first-child, .maincontent :first-child :first-child {
    margin: 0;
}

无论元素的类型如何,都会将第一个孩子的边距设置为 0。

可以做的其他事情是应用“重置样式表”,通过用零屏蔽浏览器的默认设置来撤销浏览器的默认设置。但是,我不建议您这样做,因为浏览器的默认设置在大多数情况下实际上是有意义的,并且将它们全部重置可能会导致令人不安的效果。

于 2010-08-04T22:28:50.550 回答
0

Have you tried another element than a H1? I believe the problem comes from the H1 element having margins by default and maybe that's what "pushing" the div down and leaving a gap. By the way, are you using Firefox's plugin Firebug to test CSS? It's really powerful and lets you modify on-the-fly.

于 2010-08-04T22:29:34.913 回答
0

I would say this is a problem due to browser default css settings, like those applied to h1 p, etc.

One way to get rid of this is to use some "reset" css like the one in 960grid : here

From my experience, it works fine :)

于 2010-08-04T22:34:22.580 回答
0

Maybe because margins are collapsing. Try to add

padding: 0 1px 0 1px;

to img or div or both.

于 2010-08-04T22:43:24.790 回答
0

The <img /> tag is rendered inline by default. Try display: block.

于 2013-08-14T09:21:11.740 回答