Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

css - How to disable margin collapse between sibling elements

Probably this is very stupid and well-known trick, but I haven't found any fix yet. I've tried "overflow", "content: ' '; display: table;", padding and 1px border. No success. So I've made small example to this problem.

There are 2 block elements: header with bottom margin and footer with top margin. The task is to make margins add together: 50 + 49 = 99 px!

.main-header {
  margin-bottom: 50px;
}
.main-footer {
  margin-top: 49px;
}
<h1>if distance btw H.&amp;F. is 99 px then margins don't collapse! Unfortunatelly, is is</h1>

<header class="main-header">
  HEADER Lorem ipsum dolor.
</header>

<footer class="main-footer">
  FOOTER <span>&copy;2015 Lorem ipsum dolor.</span>
</footer>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use Flexbox because it doesn't have collapsing margins.

.content {
  display: flex;
  flex-direction: column;
}

.main-header {
  margin-bottom: 50px;
}
.main-footer {
  margin-top: 49px;
}
<div class="content">
  <header class="main-header">
    HEADER Lorem ipsum dolor.
  </header>

  <footer class="main-footer">
    FOOTER <span>&copy;2015 Lorem ipsum dolor.</span>
  </footer>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...