伪元素破坏 justify-content:flexbox 布局中的空格 [英] Pseudo elements breaking justify-content: space-between in flexbox layout

查看:34
本文介绍了伪元素破坏 justify-content:flexbox 布局中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在父 div 中有三个 div,它们使用以下方法隔开:

display: flex;对齐内容:间隔;

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

codepen.io

.container {宽度:100%;显示:弹性;对齐内容:间隔;填充顶部:50px;背景:灰色;}.container div {背景:红色;高度:245px;宽度:300px;}.容器:之前{内容: '';显示:表;}.容器:在{之后清楚:两者;内容: '';显示:表;}

<div></div><div></div><div></div>

解决方案

简答

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

说明

弹性容器上的

::before::after 伪元素成为弹性项目.

来自规范:

<块引用>

4.弹性项目

Flex 容器的每个 in-flow 子项都成为一个 Flex 项目.

换句话说,在正常流程中(即,非绝对定位)的 flex 容器的每个子项都被视为一个 flex 项.

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

以下是来自 Firefox 文档的对这种渲染行为的进一步确认:

<块引用>

In-flow ::after::before 伪元素现在是 flex项目(错误 867454).

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

在此处查看我的回答以获取有关将 justify-content 弄乱的伪元素的说明:

I have three divs inside a parent div that are being spaced out using:

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

However, the parent div has an :after on it which is making the three divs not go out to the edge of parent div. Is there a way to have flexbox ignore the :before and :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>

解决方案

Short Answer

In CSS, there is currently no 100% reliable way to prevent pseudo-elements from impacting the justify-content: space-between calculation.

Explanation

::before and ::after pseudo elements on a flex container become flex items.

From the spec:

4. Flex Items

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

In other words, each child of a flex container that is in the normal flow (i.e., not absolutely positioned), is considered a flex item.

Most, if not all, browsers interpret this to include pseudo-elements. The ::before pseudo is the first flex item. The ::after item is the last.

Here is further confirmation of this rendering behavior from Firefox documentation:

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

One possible solution to your problem is to remove the pseudo-elements from the normal flow with absolute positioning. However, this method may not work in all browsers:

See my answer here for illustrations of pseudo elements messing up justify-content:

这篇关于伪元素破坏 justify-content:flexbox 布局中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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