伪元素破坏 justify-content: flexbox 布局中的空格

新手上路,请多包涵

我在一个父 div 中有三个 div,它们被隔开使用:

 display: flex;
justify-content: space-between;

但是,父 div 上有一个 :after ,这使得三个 div 不会超出父 div 的边缘。有没有办法让 flexbox 忽略 :before:after

codepen.io

 .container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-top: 50px;
  background: gray;
}

.container div {
    background: red;
    height: 245px;
    width: 300px;
  }
.container:before {
    content: '';
    display: table;
  }
.container:after {
    clear: both;
    content: '';
    display: table;
  }
 <div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>

原文由 Parzi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 662
2 个回答

简答

在 CSS 中,目前没有 100% 可靠的方法来防止伪元素影响 justify-content: space-between 计算。

解释

::before::after 弹性容器上的伪元素成为弹性项目。

从规格:

4.弹性项目

弹性容器的每个流入子容器都成为一个弹性项目。

换句话说,处于正常流中(即非绝对定位)的弹性容器的每个子元素都被视为弹性项目。

大多数(如果不是全部)浏览器将其解释为包含伪元素。 ::before 伪是第一个弹性项目。 ::after 项目是最后一项。

以下是 Firefox 文档对这种呈现行为的进一步确认:

流中 ::after::before 伪元素现在是弹性项目错误 867454 )。

您的问题的一种可能解决方案是使用绝对定位从正常流中删除伪元素。但是,此方法可能不适用于所有浏览器:

请在此处查看我的答案,以了解伪元素混乱的插图 justify-content

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果这是一个继承的属性,只需覆盖它

 .container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-top: 50px;
  background: gray;
}

.container div {
    background: red;
    height: 245px;
    width: 100px;
}

/* definitions from a framework */
.container:before {
    content: '';
    display: table;
  }
.container:after {
    clear: both;
    content: '';
    display: table;
  }

/* definitions override */
.container.flexcontainer:before,
.container.flexcontainer:after {
   display: none;
}
 <div class="container flexcontainer">
  <div></div>
  <div></div>
  <div></div>
</div>

原文由 vals 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题