孩子之间的flexbox边距崩溃 [英] flexbox margin collapsing between children

查看:98
本文介绍了孩子之间的flexbox边距崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2个具有display:block边距的容器内的元素折叠,但与display:flex不起作用!
示例

2 element inside a container with display:block margins collapse, but with display:flex is not working ! example

  .wrapper {
  width: 50%;
  margin: 0 auto;
}
.container {
  display: flex;
  // display: block;
  flex-flow: column nowrap;
  background-color: green;
}
h1 {
  background-color: #777;
  margin-bottom: 20px;
}
p {
  background-color: #ccc;
  margin-top: 15px;
}


推荐答案

当一个使用 display:flex 。如果您想进一步了解一般的崩溃边距,请看以下几篇文章:

Margins does not collapse when one use display: flex. If you want to know more about collapse margins in general, here is a couple of articles to start with:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
  • https://css-tricks.com/what-you-should-know-about-collapsing-margins/

作为一种解决方法,要使其行为类似于 display:block ,您可以执行以下操作,在其中将 flex 类添加到具有显示功能的容器中:flex ,仅定位到 h1 p

As a workaround, to make it behave similar to display: block, you could do something like this, where you add a flex class to container's that has display: flex, to target only h1 and p.

如果您不能手动执行此操作,则脚本可以为您完成该操作。

.wrapper {
  width: 50%;
  margin: 0 auto;
}
.container {
  display: flex;
  /* display: block; */
  flex-flow: column nowrap;
  background-color: green;
}
h1 {
  background-color: #777;
  margin-bottom: 20px;
}
p {
  background-color: #ccc;
  margin-top: 15px;
}


/* custom classes to remove margin */
.container.flex h1:first-child {
  margin-top: 0;
}
.container.flex p:last-child {
  margin: 0;
}

<div class="wrapper">
  <div class="container flex">
    <h1>header h1</h1>
    <p>plain text</p>
  </div>
</div>

这篇关于孩子之间的flexbox边距崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆