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

如何使用figure和figcaption实现图片上方文本定位

最佳实现方案

要实现标题、副标题及正文在图片上方且居中对齐的效果,你可以通过调整HTML结构结合CSS Flexbox布局来完成,以下是优化后的完整代码:

<!DOCTYPE html>
<html>
<head>
<style>
.Container {
  max-width: 960px; /* 限制容器宽度,避免内容过宽 */
  margin: 0 auto; /* 让容器水平居中 */
}

.fig {
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
  align-items: center; /* 所有子元素水平居中 */
  gap: 1rem; /* 控制文字区域与图片的间距 */
}

.text-content {
  text-align: center; /* 文字内容居中对齐 */
}

.text-content h1, .text-content h2 {
  margin: 0.5rem 0; /* 调整标题间距,替代原代码的负margin */
}

.fig img {
  width: 100%; /* 图片自适应容器宽度 */
  height: auto; /* 保持图片比例 */
}
</style>
</head>
<body>
<div id="Container" class="Container"> 
  <figure class="fig">
    <div class="text-content">
      <h1 id="Heading">This is a heading</h1>
      <h2 id="Subheading">This is a sub heading</h2>
      <p>This is the body text</p>
    </div>
    <img src="https://cdn.pixabay.com/photo/2016/10/26/19/00/domain-names-1772243_960_720.jpg" alt="Domain names image">
  </figure>
</div>
</body>
</html>

关键优化点说明:

  • 结构调整:将文字内容放在<img>标签之前,确保视觉上文字在图片上方;用<div class="text-content">统一包裹文字元素,便于统一控制样式。
  • Flexbox布局:给<figure>设置display: flex和flex-direction: column,配合align-items: center实现子元素水平居中、垂直有序排列。
  • 移除负margin:原代码的负margin会导致元素重叠、布局混乱,改用margin和gap控制合理间距。
  • 响应式适配:图片设置width: 100%和height: auto,保证图片自适应容器宽度且不破坏比例。
  • 文字居中:通过.text-content的text-align: center让标题、副标题及正文全部居中对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 05:18:25