0

When I have a margin on an h2 element, the margin is outside the parent div, so the background of the parent div doesn't cover the margin.

If I make it a padding it fixes.

I want the second behavior with padding, where the gray background is covering the margin.

But this doesn't work with margin, I want to know why it doesn't work with margin and works with padding, and I want it to work with margin usage.

html, body {
  padding: 0;
  margin: 0;
}

.section {
  background: #ccc;
}

.margin {
  margin: 1em 0;
}

.padding {
  padding: 1em 0;
}
<div class="section">
<div id="app">
  <h2 class="margin"> Title </h2>
</div>
</div>
<p>Content</p>
<div class="section">
<div id="app">
  <h2 class="padding"> Title2 </h2>
</div>
</div>
eguneys
  • 6,028
  • 7
  • 31
  • 63

2 Answers2

0

Try to display your container elements as block elements to constrain the child elements.

section {
display:block; width:100%; background: #ccc;
}
Nathan
  • 58
  • 5
0

Margin is space between two elements while the padding is space within the elements.

Your background applies to only elements and not to space between elements i.e. the margin.

html, body {
  padding: 0;
  margin: 0;
}

.section {
  background: #ccc;
  border:1px solid transparent;
}

.margin {
  margin: 1em 0;
}

.padding {
  padding: 1em 0;
}
<div class="section">
<div id="app">
  <h2 class="margin"> Title </h2>
</div>
</div>
<p>Content</p>
<div class="section">
<div id="app">
  <h2 class="padding"> Title2 </h2>
</div>
</div>
Dhruvi Makvana
  • 895
  • 5
  • 17