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

适配图片宽度的浮动figure及figcaption跨Firefox与Chrome CSS解决方案

跨浏览器适配:固定居中figure及figcaption匹配图片宽度的解决方案

问题背景

我有一个固定居中的figure容器,内部图片尺寸由实际加载的图片决定(限制最大宽度为85%),下方配有figcaption。遇到以下跨浏览器兼容问题:

  • 使用display: table-caption设置figcaption时,Firefox中能正常匹配图片宽度,但Chrome中figcaption宽度被压缩,无法对齐图片
  • 将figure的display设为table时,Chrome显示正常,但Firefox中figure不再水平居中,且figcaption宽度不受约束,尝试width: fit-content也无效

需求:实现跨浏览器兼容的CSS方案,要求figure始终固定在页面中央,即使页面滚动也不偏移。


初始代码

HTML

<div>
  <figure>
    <img />
    <figcaption>This is some text. This is some text. This is some text. This is some text. This is some text.</figcaption>
  </figure>
</div>

CSS

div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
figure {
  position: relative;
  max-width: 85%;
  margin: auto;
  display: block;
}
img {
  width: 300px;
  height: 150px;
  background: #000;
}
figcaption {
  display: table-caption;
  caption-side: bottom;
  width: 100%;
}

仅Chrome生效的修改(Firefox存在问题)

将figure的display属性改为table,仅在Chrome中能正常显示,Firefox会出现居中失效、figcaption宽度不受约束的问题:

figure {
  display: table;
}

跨浏览器兼容解决方案

调整figure和figcaption的样式,利用inline-block配合flex容器的居中特性,同时确保figcaption宽度跟随图片:

修改后的CSS

div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
figure {
  position: relative;
  max-width: 85%;
  display: inline-block; /* 让figure宽度由内部内容决定 */
  margin: 0;
  text-align: center; /* 可选:若需要figcaption文字居中显示 */
}
img {
  max-width: 100%; /* 确保图片不超过figure的最大宽度限制 */
  height: auto; /* 维持图片原始比例 */
  /* 示例固定尺寸,实际场景可移除,由图片自身尺寸决定 */
  width: 300px;
  height: 150px;
  background: #000;
}
figcaption {
  width: 100%; /* 强制figcaption宽度与figure(即图片)一致 */
  box-sizing: border-box; /* 避免内边距/边框导致宽度溢出 */
}

方案说明

  1. figure设置inline-block:使figure的宽度由内部图片自动决定,同时配合父容器的flex布局,在所有现代浏览器中都能保持水平居中
  2. 图片设置max-width:100%:确保图片不会超出figure的max-width:85%限制,height:auto保证图片比例不会变形
  3. figcaption设置width:100%:强制figcaption宽度完全匹配figure的宽度,解决Chrome中宽度压缩、Firefox中宽度不受约束的问题
  4. box-sizing:border-box:避免figcaption的内边距或边框导致宽度超出figure范围

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:50:29