【问题标题】:flexbox margin collapsing between children [duplicate]flexbox边距在孩子之间折叠[重复]
【发布时间】:2017-09-13 22:44:46
【问题描述】:

容器内的 2 元素显示:块边距折叠,但显示:flex 不起作用! 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;
}

【问题讨论】:

  • 也许我说错了。边距顶部底部应保持不变。 .container 必须具有 display:flex 不变。在 p 和 h1 上设置 display:flex 没有给出......并且没有改变 flex-wrap 。
  • 您能否提供您正在寻找的图片或绘图?你的解释和评论不是很清楚

标签: css flexbox margin collapse


【解决方案1】:

使用display: flex 时,边距不会折叠。如果您想了解更多关于一般折叠边距的信息,可以从以下几篇文章开始:


作为一种解决方法,要使其行为类似于display: block,您可以执行以下操作,将flex 类添加到具有display: flexcontainer,以仅定位h1p

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

.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>

【讨论】:

  • 这就是我无法删除 margin-top: 15px;边距底部:20px;这个例子是继承到 flexbox 的一个更大项目的一部分。也就是说,我永远无法使用 flexbox 获得快速崩溃的边际?
  • @Petr 不,你不能使用 flexbox 实现边距折叠。那么为什么不能去掉边距呢?
  • @Petr 用更多建议更新了我的答案
  • 我可以去掉margin,但是我期待(15和20)折叠的效果
  • @Petr 好吧,在给定的情况下,我的答案是这样做的,但如果 p 的上边距高于 h1 的下边距,它应该是那个值(折叠边距使用两者中最高的),但由于flexbox 不知道,你必须告诉它。同样,一个小脚本可以解析这些元素并检查要使用的值,或者如果您在设计时知道,您可以使用不同的类来实现它
猜你喜欢
  • 2015-01-19
  • 2019-08-16
  • 2020-09-12
  • 2018-07-21
  • 1970-01-01
  • 2017-03-04
  • 2016-02-04
  • 2022-01-15
  • 1970-01-01
相关资源
最近更新 更多