css 问题为什么 flex 会影响 before 的显示效果?

2022-12-26 19:02:23 +08:00
 woshichuanqilz

这个是我的代码, 如果.square 移除 flex 特性, before 就看不见了, 为什么会这样? 我查了 mdn 没找到相关的内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .square {
            width: 100px;
            height: 100px;
            background-color: blue;
            color: white;
/* 如果去掉这个 flex before 就看不见了 */
            display: flex;
        }
        .square::before {
            content: "";
            width: 50px;
            height: 50px;
            background: lightgreen;
        }
        .square::after {
            content: "";
        }

        .text::before{
            content: "t1";
            color: red;
        }
        .text::after{
            content: "t2";
            color: red;
        }

    </style>

</head>
<body>
    <div class="square"></div>
    <p class="text">love</p>
</body>
</html>
1057 次点击
所在节点    CSS
2 条回复
renmu
2022-12-26 19:16:41 +08:00
.square::before{
display:inline-block
}

行内文本你不能设置宽高,又没内容,就不显示了。
你加了 flex 后,子元素就都被 flex 化了,用得就是另一套东西了
liyang5945
2022-12-26 19:22:40 +08:00
伪元素默认 display 是 inline

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/904803

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX