h1或p margin-top与DIV填充的总和,它们如何崩溃

时间:2016-05-24 21:28:12

标签: html css

我需要将段落和标题放在带填充的div中。但是,h1 / p的margin-top与div的填充相加并使h1 / p位于较低位置。怎么避免这个?我不需要将margin-top设置为零,我需要填充和边距折叠,如段落边距。

示例,div中的左边和上边距应该相等,但它们不相同:https://jsfiddle.net/7trhs2vp/2/

<div style="padding:1em;background:silver">
  <h1>Header</h1>
</div>

body {font-size:20px;}
h1 {margin:1em 0;}

1 个答案:

答案 0 :(得分:0)

您需要删除或调整边距或填充。填充不像边距那样崩溃。

如果您的h1p具有最高边距是容器DIV中具有填充的第一个子元素,则可以使用CSS伪选择器:first-child来定位它们以删除/调整保证金。

在下面的演示中,我为一些元素添加了边框,以帮助可视化边距的位置和不边距。

body,
h1,
p {
  margin: 0;
}

h1,
p {
  margin: 1.5rem;
  border: 1px dotted orange;
}

.container {
  padding: 1rem;
  border: 1px dashed skyblue;
}

/*
   This is applied to ANY h1 or p that is the first child
   of ANY element that is a child of a .container element.

   Place the child selector (>) between .container and/or 
   h1 and p to limit it to only child elements of .container.

  .container > h1:first-child {}
*/
.container h1:first-child,
.container p:first-child {
  margin-top: 0;
}
<div class="container">
  <h1>
   H1 Header
  </h1>
  <p>
    Content content content.
    Content content content.
    Content content content.
    Content content content.
    Content content content.
    Content content content.
  </p>
</div>

<div class="container">
  <p>
    Content content content.
    Content content content.
    Content content content.
    Content content content.
    Content content content.
    Content content content.
  </p>
  <p>
    Content content content.
    Content content content.
    Content content content.
    Content content content.
    Content content content.
    Content content content.
  </p>
</div>

演示JSFiddle