Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...