伪元素破坏 justify-content: space-flexbox 布局中的 between

Pseudo elements breaking justify-content: space-between in flexbox layout

我在父 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>

简答

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

说明

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

来自规范:

4. Flex Items

Each in-flow child of a flex container becomes a flex item.

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

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

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

In-flow ::after and ::before pseudo-elements are now flex items (bug 867454).

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

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

在父级 div 中嵌套了另一个 div 并提供了所有 flex 代码,因此伪元素不会影响它。

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

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

如果您必须这样做,您可以利用弹性项目的自动边距行为。您还需要将第一个 flex child 的左边距归零,同样需要将最后一个 flex child 的右边距归零。请参阅下面的代码笔。

Flexbox 和自动边距:https://www.w3.org/TR/css-flexbox-1/#auto-margins

Codepen 演示:http://codepen.io/anderskleve/pen/EWvxqm

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

  div {
    background: red;
    height: 245px;
    width: 300px;
    margin: 0 auto;
  }

  div:first-child {
    margin-left: 0;
  }

  div:last-child {
    margin-right: 0;
  }

  &:before {
    content:'';
    display: table;
  }

  &:after {
    clear: both;
    content: '';
    display: table;
  }
}