为什么这些div会相互排斥?

时间:2010-05-20 03:25:36

标签: css html

<html>
 <div style="width:200px;">
  <div style="background:red;height:5px"></div>
  <div style="background:yellow">
   Magnets?
  </div>
  <div style="background:green;height:5px"></div>
 </div>
</html>

Rendering with "Magnets?" wrapped in h3 tags

如果“磁铁?”,div如何不再连续?包含在段落或标题标签中?

2 个答案:

答案 0 :(得分:2)

您正在包装的元素可能具有默认边距。

答案 1 :(得分:1)

您需要将h3或p上的边距清零。

<html>
 <div style="width:200px;">
  <div style="background:red;height:5px"></div>
  <div style="background:yellow">
   <h3 style="margin:0px;">Magnets?</h3>
  </div>
  <div style="background:green;height:5px"></div>
 </div>
</html>

如果你想保留h3和其他元素的边距,那么你需要解决div折叠中元素边距的问题。有几种方法可以解决这个问题:

  1. 为div添加边框
  2. 向div添加1px边框
  3. 从元素中删除边距,然后将其添加到div中。
  4. 以下链接提供了更多信息:

    http://www.complexspiral.com/publications/uncollapsing-margins/