0

I have two divs: .content and .main-section, the second inside the first. I am adding a margin-top to .main-section and I expected to see part of .content, but it seems this has a margin-top too. Why this behavior? and How to create a margin between .content and .main-section?

body {
  margin: 0;
}

.content {
  min-height: 100vh;
  background: peru;
}

.main-section {
  background: red;
  height: calc(100vh - 30px);
  margin-top: 30px;
}
<div class="content">
  <div class="main-section">
    <p class="parragraph"> parragraph </p>
    <p class="parragraph"> parragraph </p>
  </div>
</div>

Expected:
Expected

Output:
Output

Hans Felix Ramos
  • 4,264
  • 3
  • 16
  • 40
  • 3
    [https://stackoverflow.com/questions/13573653/css-margin-terror-margin-adds-space-outside-parent-element](https://stackoverflow.com/questions/13573653/css-margin-terror-margin-adds-space-outside-parent-element) Related problem that can be solved with `overflow: auto` – masterpreenz May 26 '20 at 07:04
  • Thanks @masterpreenz. I understand, The answer provided is the link is for CSS2. Also apply for current CSS? – Hans Felix Ramos May 26 '20 at 07:18
  • 1
    yes it does apply to the current CSS.the CSS2 Spec will remain valid forever: https://meta.stackoverflow.com/a/385583/8620333 – Temani Afif May 26 '20 at 08:24

3 Answers3

4

As masterpreenz said in the comment, use overflow:auto to solve this. You can read more here about it: https://www.w3.org/TR/CSS2/box.html#collapsing-margins

body {
  margin: 0;
}

.content {
  min-height: 100vh;
  background: peru;
  overflow: auto;
}

.main-section {
  background: red;
  height: calc(100vh - 30px);
  margin-top: 30px;
}
<div class="content">
  <div class="main-section">
    <p class="parragraph"> parragraph </p>
    <p class="parragraph"> parragraph </p>
  </div>
</div>
Tibbelit
  • 1,215
  • 10
  • 17
1

you should set padding-top for your parent div to make it what you want

body {
  margin: 0;
}

.content {
  min-height: 100vh;
  background: peru;
  padding-top:30px;
}

.main-section {
  background: red;
  height: calc(100vh - 30px);
}
<div class="content">
  <div class="main-section">
    <p class="parragraph"> parragraph </p>
    <p class="parragraph"> parragraph </p>
  </div>
</div>
Yasaman.Mansouri
  • 550
  • 1
  • 3
  • 13
1

if you use margin: top effect, then the main section can also go out of the content block if overflow condition is not specified, so it's better to use padding: which specifies that the main section will begin after the given value of padding: top.

VR7
  • 112
  • 3
  • 16