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

如何实现容器内多文本元素垂直居中且左对齐、上下堆叠

问题描述

我有一个section,分为两部分,希望其中class为col2的容器内的文本垂直居中且左对齐。目前仅实现了h1元素的垂直居中,但添加其他文本元素后,位置错乱,无法上下堆叠。

当前效果

当前效果

HTML代码

<section class="outer">
    <div class="col2">
        <h2>P E R F U M E</h2>
        <h1>Gabrielle<br> Essence Eau<br> De Parfum</h1>
        
        <p>A floral, solar and voluptuous<br> interpretation composed by<br> Olivier Polge, 
          Perfumer-Creator<br> for the House of CHANEL.
        </p>
    </div>
</section>

CSS代码

.col2 {
    position: absolute;
    display: table;
    width: 350px;
    height: 600px;
    background-color: white;
    right: 0;
    text-align: left;
}


.col2 h1 {
    display: table-cell;
    vertical-align: middle;
    text-align: left;
    padding: 20px;
    height: fit-content;
    font-family: 'Fraunces';
}

预期效果

预期效果

我尝试过给容器设置display: table,文本元素设置display: table-cell(曾误写为table--cell),仅单个元素时生效,添加其他元素后失效;也尝试过line-height,但未达到预期效果。


解决方案

你之前用table和table-cell的方式只适合单个元素垂直居中,多个元素时会因为每个table-cell元素并列显示导致布局错乱。推荐用Flex布局实现,简单高效:

修改后的CSS代码:

.col2 {
    position: absolute;
    width: 350px;
    height: 600px;
    background-color: white;
    right: 0;
    /* 启用Flex布局 */
    display: flex;
    flex-direction: column; /* 让子元素垂直堆叠 */
    justify-content: center; /* 整体垂直居中 */
    align-items: flex-start; /* 内容左对齐 */
    padding: 20px; /* 避免内容贴容器边缘 */
}

.col2 h1 {
    font-family: 'Fraunces';
    margin: 12px 0; /* 调整标题间距 */
}

.col2 h2, .col2 p {
    margin: 12px 0; /* 统一其他元素上下间距 */
}

关键说明

  1. flex-direction: column确保h2、h1、p垂直排列,解决了多元素无法堆叠的问题。
  2. justify-content: center让所有子元素整体在容器内垂直居中。
  3. align-items: flex-start强制所有内容左对齐,符合需求。
  4. 给子元素加margin可以优化元素间的留白,让布局更美观。

如果需要兼容旧浏览器,也可以用Grid布局替代:

.col2 {
    position: absolute;
    width: 350px;
    height: 600px;
    background-color: white;
    right: 0;
    display: grid;
    place-content: center start; /* 垂直居中+水平左对齐 */
    padding: 20px;
}

.col2 h1 {
    font-family: 'Fraunces';
    margin: 12px 0;
}

.col2 h2, .col2 p {
    margin: 12px 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:35:37