You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS问题:如何在flexbox中让h1的::before/::after文本居中

解决h1伪元素::before/::after文本居中问题

你的问题出在几个关键CSS设置上:

  • 伪元素默认是inline元素,无法直接生效width/height属性,也没法通过布局属性实现文本居中
  • font-size未添加单位(如px),导致字体样式不生效
  • 百分比高度依赖父元素的明确高度,否则无法正确渲染

下面是修改后的完整CSS代码,可解决文本居中问题:

/* ::Before Heading */
.flex-container-heading h1::before{
    content: "This is a very cool";

    /* General */
    background: red;
    display: flex;
    justify-content: center; /* 水平居中文本 */
    align-items: center;     /* 垂直居中文本 */

    /* Sizing */
    height: 40px; /* 用固定高度替代百分比,避免父元素高度不确定的问题 */
    width: 100%;

    /* Text */
    color: white;
    font-size: 30px; /* 补上px单位 */
    font-weight: 900;
}

/* Heading */
.flex-container-heading h1{
    /* General */
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%; /* 让h1占满容器宽度,确保伪元素的100%width生效 */
    margin: 0; /* 清除默认margin,避免不必要的间距 */

    /* Text */
    color: white;
    font-size: 40px; /* 补上px单位 */
    font-weight: 900;
}

/* ::After Heading */
.flex-container-heading h1::after{
    content: "Isn't it aye?";

    /* General */
    background: red;
    display: flex;
    justify-content: center;
    align-items: center;

    /* Sizing */
    height: 40px;
    width: 100%;

    /* Text */
    color: white;
    font-size: 30px; /* 补上px单位 */
    font-weight: 900;
}

替代方案(不用flex布局)

如果你习惯用块级元素的方式实现居中,也可以这样设置伪元素:

.flex-container-heading h1::before{
    /* ...其他样式 */
    display: block;
    text-align: center; /* 水平居中 */
    line-height: 40px; /* 与height值一致,实现垂直居中 */
}

内容的提问来源于stack exchange,提问作者Trevn Jones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:31:01