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

为何justify-content:center无法使.experience容器内元素居中?

问题解析与解决方案

核心原因

当设置flex-direction: column时,justify-content控制的是垂直方向(主轴)的元素对齐,而你要实现的是水平居中,得用align-items: center来控制交叉轴(水平方向)的对齐。

另外,#experience_content里的img和p无法居中,是因为你没给这个容器设置justify-content: center(默认是flex-start左对齐),好在它默认继承父容器宽度(100%),加了属性就能生效。

修正后的代码

<html>
<head>
<style>
/* 给body和html清掉默认边距,避免页面出现滚动条或留白 */
body, html {
    margin: 0;
    padding: 0;
}

.experience {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center; /* 新增:让子元素水平居中 */
    min-height: 100vh; /* 可选:让容器占满视口高度,实现垂直方向居中 */
}

#experience_content {
    display: flex;
    gap: 10px;
    justify-content: center; /* 新增:让内部img和p水平居中 */
    align-items: center; /* 可选:让图片和文字垂直对齐,避免基线不齐 */
}
</style>
</head>
<body>
    <section class="experience">
        <h2>Work Experience</h2>
        <div id="experience_content">
            <img src=./images/supermarket.jpg width="260" height="195" alt=" shopping center">
            <p> Please help me solve this stupid problem. I beg you.</p>
        </div>
    </section>
</body>
</html>

补充说明

  • 若只需要h2和#experience_content水平居中,仅给.experience添加align-items: center即可;如果要让它们在页面垂直居中,再加上min-height: 100vh。
  • #experience_content的align-items: center是为了优化图片和文字的垂直对齐效果,可根据实际需求选择是否保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:43:15