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

实现等高且图片不裁剪的多figure元素横向布局

解决方案:等高Figure布局(图片保持原比例不裁剪)

要实现一行内多个figure元素等高,同时图片保持原始宽高比且不被裁剪,可以通过CSS Grid + Flexbox + 图片容器控制的组合方案实现,替代会导致裁剪的object-fit: cover。

核心实现思路

  1. 用Grid布局让所有figure自动分配水平空间并强制等高
  2. 给每个figure内部用Flexbox分配图片区和标题区的空间,确保标题始终在底部
  3. 为图片单独设置容器,利用object-fit: contain让图片在容器内按比例完整显示,同时容器高度由等高的figure统一控制

完整代码示例

HTML结构

<div class="container">
  <figure style="--w:100; --h:100;">
    <div class="img-wrapper">
      <img src="https://placehold.co/100x100/f08/fff">
    </div>
    <figcaption>正方形图</figcaption>
  </figure>
  <figure style="--w:200; --h:40;">
    <div class="img-wrapper">
      <img src="https://placehold.co/200x40/0f8/fff">
    </div>
    <figcaption>宽扁图</figcaption>
  </figure>
  <figure style="--w:150; --h:200;">
    <div class="img-wrapper">
      <img src="https://placehold.co/150x200/8f0/fff">
    </div>
    <figcaption>高瘦图</figcaption>
  </figure>
  <figure style="--w:250; --h:200;">
    <div class="img-wrapper">
      <img src="https://placehold.co/250x200/f80/fff">
    </div>
    <figcaption>宽高图</figcaption>
  </figure>
</div>

CSS样式

.container {
  display: grid;
  grid-auto-flow: column; /* 水平排列元素 */
  gap: 1rem; /* 元素间间距 */
  padding: 1rem;
}

figure {
  display: flex;
  flex-direction: column;
  margin: 0;
  height: 100%; /* 继承Grid容器的等高特性 */
  border: 1px solid #eee;
  padding: 0.5rem;
}

.img-wrapper {
  flex: 1; /* 占满figure除标题外的所有高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  /* 利用自定义属性固定容器宽高比,避免布局跳动 */
  aspect-ratio: var(--w)/var(--h);
}

.img-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 核心:图片按原比例完整显示,不裁剪 */
}

figcaption {
  text-align: center;
  margin-top: 0.5rem;
}

关键细节说明

  • grid-auto-flow: column让容器内的figure自动水平排列,Grid默认会强制所有列高度一致,直接实现等高效果
  • figure使用flex-direction: column垂直分布内容,flex:1的img-wrapper自动填充剩余空间,确保标题始终固定在底部
  • object-fit: contain是解决图片裁剪问题的核心:它会让图片在容器内保持原始宽高比完整展示,若容器与图片比例不一致,会自动留空适配,完全避免裁剪
  • 保留原有的--w和--h自定义属性,通过aspect-ratio为图片容器预留比例空间,优化布局加载体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:03:23