Skip to content

[Bug] H5 Image mode="aspectFit" does not center the inner image horizontally #19463

Description

@jifenjiliang

请先确认

  • 我已搜索并确定这个提交不是重复的

Taro 版本

v4

相关领域

H5 组件库

使用框架

React

相关平台

  • Web 端(H5)

小程序基础库版本

不适用(问题仅出现在 H5 端)

问题描述

在 Taro 4.2.0 H5 端使用 <Image mode="aspectFit" /> 时,内部图片只进行了垂直居中,没有显式进行水平居中。当图片宽高比与 Image 容器不一致、图片适配后未占满容器宽度时,绝对定位的内部 img 会依赖水平方向的 static position,导致图片没有在容器内水平居中。

当前 packages/taro-components/src/components/image/style/index.scss 中的样式为:

&-aspectfit {
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
}

同文件的 aspectFillcenter 等模式已通过 left: 50%translate(-50%, -50%) 实现双轴居中,但 aspectFit 缺少对应的水平定位。

期望 aspectFit 在图片未铺满容器时也能在水平和垂直方向居中,与小程序原生 image mode="aspectFit" 的表现一致:

&-aspectfit {
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

目前项目侧需要添加覆盖样式才能修正:

.icon img {
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

复现链接

&-aspectfit {
max-width: 100%;
max-height: 100%;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}

复现步骤

  1. 创建一个 Taro 4 React 项目,并启用 H5 构建。
  2. 准备一张宽高比为 1:2 的图片,例如 16x32.png
  3. 在一个正方形 Image 容器内使用 aspectFit
<Image
  style={{ width: '48px', height: '48px', background: '#eee' }}
  src='/assets/16x32.png'
  mode='aspectFit'
/>
  1. 执行 H5 构建并在浏览器中检查 .taro-img__mode-aspectfit
  2. 图片按高度缩放后宽度小于容器宽度,但没有在容器内水平居中。
  3. 添加 left: 50%; transform: translate(-50%, -50%); 后,图片恢复双轴居中。

环境信息

Taro CLI 4.2.0 environment info:
  System:
    OS: macOS 15.7.7
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.23.1
    Yarn: 1.22.22
    npm: 6.14.6
  npmPackages:
    @tarojs/cli: 4.2.0
    @tarojs/components: 4.2.0
    @tarojs/plugin-framework-react: 4.2.0
    @tarojs/plugin-platform-h5: 4.2.0
    @tarojs/react: 4.2.0
    @tarojs/runtime: 4.2.0
    @tarojs/taro: 4.2.0
    @tarojs/vite-runner: 4.2.0
    react: 18.3.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions