伪元素打破了对齐内容:flexbox布局中的空格

时间:2016-11-18 22:29:08

标签: html css css3 flexbox pseudo-element

我在父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>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:16)

简答

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

说明

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

来自规范:

  

4. Flex Items

     

Flex容器的每个in-flow子项都变为flex项。

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

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

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

  

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

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

请参阅我的答案,了解虚假元素的插图justify-content

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

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

答案 3 :(得分:0)

如果必须这样做,您可以利用弹性项目上的自动边距行为。您还需要将第一个flex子元素的左边距和最后一个flex子元素的右边距相等。请参阅下面的代码。

Flexbox&amp;自动边距: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;
  }
}