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

如何用CSS实现Div内图文的水平垂直居中及紧密排布?

问题描述

需要实现div内文字与图片同时水平和垂直居中,要求:

  • 已为div设置宽度,避免内容贴靠容器边缘
  • 图文紧密排布,调换二者顺序时仍能生效
问题原因分析

原代码使用justify-content: space-between会让元素强制分布在容器两端,导致图文分散;同时给子元素设置margin: 0 auto属于flex布局下的冗余设置,无法实现紧密居中的效果。

解决方案代码

修改后CSS代码

.joron_description {
    display: flex;
    /* 替换space-between,让整体内容水平居中 */
    justify-content: center;
    align-items: center;
    width: 100%;
    /* 可选:添加内边距避免内容贴靠容器边缘 */
    padding: 0 20px;
    /* 控制图文间距,实现紧密排布,调换顺序自动适配 */
    gap: 20px;
}

.joron_description img {
    height: 229px;
    width: 210px;
}

.joron_description .joron-text {
    background-color: rgba(7, 15, 43, 0.8);
    border-radius: 10px;
    text-align: center;
    padding: 10px 30px;
}

HTML代码(可直接调换img与文字容器顺序)

<div class="joron_description">
  <img src="/assets/about_img/joron-about_img.png" alt="Joron's Image">
  <div class="joron-text">
    <p>
      Joaquin Aaron P. Recio | The Lead Programmer of Hug Haven.
    </p>
  </div>
</div>
关键修改说明
  • 用justify-content: center替代space-between,确保整体内容在容器水平方向居中
  • 添加gap属性控制图文间距,实现紧密排布,调换顺序时间距自动保持一致
  • 移除子元素冗余的margin: 0 auto,避免干扰flex布局的对齐逻辑
  • 可选添加容器内边距,防止内容贴靠容器边缘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:05:09