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

如何实现文本单独居中且图片紧邻其旁的响应式CSS布局

解决方案

提供两种无需硬编码偏移、支持响应式的实现方案:

方案1:负边距实现(兼容性最优)

核心逻辑是通过负右边距抵消图片宽度对文本居中的影响,让文本始终对齐页面中心,图片紧跟文本排布即可。

完整CSS代码

* {
  font-size: 30px;
  font-weight: normal;
}

p {
  text-align: center;
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
}

h2 {
  text-align: center;
  /* 负边距值和图片宽度保持一致即可,图片宽度变化时同步修改该值 */
  margin-right: -200px;
  /* 如需避免文本过长被挤压换行可保留该行,不需要可删除 */
  white-space: nowrap;
}

img {
  width: 200px;
  height: 200px;
  /* 可自行调整文本和图片的间距 */
  margin-left: 10px;
}

对应HTML代码

<p>This text is centered</p>

<header>
  <h2>This text is centered</h2>
  <img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png">
</header>

该方案所有元素都在常规文档流中,无需绝对定位,任意屏幕尺寸下文本都能保持居中,图片始终紧贴文本右侧。

方案2:Grid三列布局(逻辑更直观)

如果不想使用负边距,可以通过Grid三列布局实现,左右列自动填充剩余空间,保证中间内容的中心和页面中心对齐:

完整CSS代码

* {
  font-size: 30px;
  font-weight: normal;
}

p {
  text-align: center;
}

header {
  display: grid;
  /* 三等分布局,左右列占满剩余空间,中间列宽度自适应内容 */
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
}

.content-wrap {
  grid-column: 2 / 3;
  display: flex;
  align-items: center;
  /* 可自行调整文本和图片的间距 */
  gap: 10px;
}

h2 {
  margin: 0;
}

img {
  width: 200px;
  height: 200px;
}

对应HTML代码

<p>This text is centered</p>

<header>
  <div class="content-wrap">
    <h2>This text is centered</h2>
    <img src="https://www.freeiconspng.com/uploads/cute-rabbit-png-12.png">
  </div>
</header>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:45:03