【问题标题】:css vertical gap between divsdiv之间的css垂直间隙
【发布时间】:2011-02-27 20:33:51
【问题描述】:

我知道这是一个常见问题,但我似乎找不到有效的解决方案。我有这样的设置:

 <div id="wrapper">
  <div class="content-area-top"></div>
  <div class="content-area">
   <h1>Title</h1>
   some other text
  </div>
 </div>

.content-area-top {
  height: 12px;
  width: 581px;
  background-image: url(images/content-top.jpg);
 }

.content-area {
margin-left: 10px;
margin-right: 10px;
    background-color: #e9ecfd;
 }

问题在于 .content-area-top 和 .content-area 之间存在差距。 .content-area-top div 的大小可以包含一个背景图像,它可以为我提供我想要的圆角。

我知道这个问题是由于 H1 标签有一个(浏览器默认的)上边距设置(.67em),但我不愿意将它的边距设置为 0,我不明白为什么它的边距在其包含 div 的“外部”应用。

我在 Mac 上使用 chrome,但 Firefox 也有同样的问题。这可能是一些众所周知的修复方法,但我找不到针对我的案例的解决方案。

【问题讨论】:

  • 使用 css 重置文件,您将在浏览器中获得更一致的行为。 developer.yahoo.com/yui/reset
  • 我试过了,它折叠了两个 div 之间的空间,但是一旦我在 h1 上放回带边距的样式,间隙就会重新出现。真正的问题似乎是 h1 上的任何边距都超出了它周围的 div,在我看来,边距应该完全包含在包含的 div 内。
  • 这里还有一个非常相似的问题:stackoverflow.com/questions/2176520/…,但没有很好的答案。如果我让 .content-area 块具有 display:inline-block,它会按预期工作,但这并不是在所有浏览器中都实现得很好。
  • 实际上链接到另一个引用问题 (reference.sitepoint.com/css/collapsingmargins) 的文章确实有一些指示。答案是 H1 上的边距与其父边距(在本例中为 0)折叠,因此父 div 采用 H1 边距。为防止这种情况发生,父 div (.content-area) 需要设置填充集或边框或其他设置以防止崩溃(在我的情况下,这将我的两个 div 正确组合在一起)

标签: html css


【解决方案1】:

相关问题请参见此处:

Why would margin not be contained by parent element?

其中介绍了一篇关于边距折叠的精彩文章:

http://reference.sitepoint.com/css/collapsingmargins

这篇文章确实有一些指示。

答案是 H1 上的边距与其父级 (.content-area) 边距(在本例中为 0)折叠,因此父 div 占据 H1 边距。为防止这种情况发生,父 div (.content-area) 需要设置填充集或边框或其他设置以防止崩溃(在我的情况下,这将我的两个 div 正确地组合在一起)

【讨论】:

  • +1,非常好。要重复这个答案,只需在 #content-area 上设置一个 padding-top
  • 非常感谢,这让我很难过
【解决方案2】:

如果它们之间有边界,则边距不应折叠。因此,您可以添加隐藏边框以防止边距塌陷。

以下内容在我测试的 FF、Chrome 和 IE 版本中对我有用。

<!-- Set the border-color to your background color. 
     If default white background colour use #FFFFFF -->
<div style="background-color: #8DB3E2; border-color: #8DB3E2; border-style:solid; border-width:1px; "> 

  <p >Paragraph 1 in blue box</p>

  <p >Paragraph 2 in blue box</p>

  </div>

  <!-- No space here thanks -->

  <div style="background-color: #9BBB59; border-color: #9BBB59; border-style:solid; border-width:1px; "> 

  <p >Paragraph 1 in green box</p>

  <p >Paragraph 2 in green box</p>

  </div> 

【讨论】:

    【解决方案3】:

    尝试提供有效的文档类型。它对我有用:)

    参考这个:A list apart 已经说得很漂亮了!

    瑜伽

    【讨论】:

      【解决方案4】:

      试试这个方法:

      #content-area-top {
        width:581px;
        height:12px;
        float:left;
        background-image:url("images/content-top.jpg");
      }
      
      #content-area {
        width:561px; /* substract margin left & right values from it's width */
        float:left;
        display:inline; /* prevent ie6-double-margin bug */
        margin:0 10px;
        background-color:#e9ecfd;
      }
      
      #wrapper {
        width:581px;
        float:left;
      }
      

      【讨论】: