请先确认
Taro 版本
v4
相关领域
H5 组件库
使用框架
React
相关平台
小程序基础库版本
不适用(问题仅出现在 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%);
}
同文件的 aspectFill、center 等模式已通过 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%); |
|
} |
复现步骤
- 创建一个 Taro 4 React 项目,并启用 H5 构建。
- 准备一张宽高比为 1:2 的图片,例如
16x32.png。
- 在一个正方形 Image 容器内使用
aspectFit:
<Image
style={{ width: '48px', height: '48px', background: '#eee' }}
src='/assets/16x32.png'
mode='aspectFit'
/>
- 执行 H5 构建并在浏览器中检查
.taro-img__mode-aspectfit。
- 图片按高度缩放后宽度小于容器宽度,但没有在容器内水平居中。
- 添加
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
请先确认
Taro 版本
v4
相关领域
H5 组件库
使用框架
React
相关平台
小程序基础库版本
不适用(问题仅出现在 H5 端)
问题描述
在 Taro 4.2.0 H5 端使用
<Image mode="aspectFit" />时,内部图片只进行了垂直居中,没有显式进行水平居中。当图片宽高比与 Image 容器不一致、图片适配后未占满容器宽度时,绝对定位的内部img会依赖水平方向的 static position,导致图片没有在容器内水平居中。当前
packages/taro-components/src/components/image/style/index.scss中的样式为:同文件的
aspectFill、center等模式已通过left: 50%和translate(-50%, -50%)实现双轴居中,但aspectFit缺少对应的水平定位。期望
aspectFit在图片未铺满容器时也能在水平和垂直方向居中,与小程序原生image mode="aspectFit"的表现一致:目前项目侧需要添加覆盖样式才能修正:
复现链接
taro/packages/taro-components/src/components/image/style/index.scss
Lines 25 to 31 in dd4f0fb
复现步骤
16x32.png。aspectFit:.taro-img__mode-aspectfit。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