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

使用Flexbox实现垂直居中时文字无法纵向堆叠如何解决?

问题原因

  • 你为.hero-text设置了display: flex属性,flex布局默认主轴方向为横向(flex-direction: row),所以内部的h1、h5、h6元素会沿横向排列,而非默认的纵向堆叠
  • 代码中混用flex布局和table相关布局属性,逻辑冗余混乱,额外增加的.hero-row和display: table、display: table-cell等属性完全没有必要,反而会干扰正常布局

修正后代码

HTML(可直接删掉无用的hero-row层,简化结构)

<div>
  <div class="hero-section">
    <div class="hero-text">
      <h1>Title</h1>
      <h5>Title</h5>
      <h6>Title</h6>
    </div>
  </div>
</div>

SCSS

.hero-section {
    background-image: url("https://images.unsplash.com/photo-1622495546323-5dac33dedb01?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=967&q=80");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    height: 100vh;
    width: 100%;
    margin: auto;
    /* 开启flex实现子元素垂直居中 */
    display: flex;
    align-items: center;
    /* 你原来要左对齐就保留justify-content: left,要整体居中就改center */
    justify-content: left;
    padding-left: 2rem; /* 可以加个内边距避免文字贴边 */

    .hero-text {
        color: #fff;
        /* 删掉冗余的table、flex属性,子元素自动纵向堆叠 */
        /* 如果需要文本内部也水平居中可以加text-align: center */
    }
}

如果确实需要保留.hero-text的flex属性,只需要给它加一行flex-direction: column即可:

.hero-text {
    color: #fff;
    display : flex;
    flex-direction: column;
    /* 文本水平居中可加 align-items: center */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 13:15:05