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

Mantine Flex与Stack布局中Image组件不显示问题解决求助

Mantine布局问题:预览图与垂直输入框并排时图片宽度为0的解决方法

需求描述

想要实现预览图与两个垂直堆叠的输入框横向并排的布局,原生CSS实现方式如下:

原生CSS实现代码

#container {
  display: flex;
  width: 100%;
}
#container img {
  object-fit: contain;
}
#inputs {
  flex: 1;
  display: flex;
  flex-direction: column;
}
<div id="container">
  <img src="https://picsum.photos/id/17/200/300">
  <div id="inputs">
    <input name="url" value="https://picsum.photos/id/17/200/300">
    <input name="alt" value="Image alt goes here">
  </div>
</div>

(理想状态下不需要指定#container的高度,让其自适应输入框总高度)

当前Mantine实现问题

使用Mantine组件尝试实现时,图片宽度变为0无法显示,代码如下:

<Flex>
    <Image src="https://picsum.photos/id/17/200/300" />
    <Stack flex="1">
        <TextInput label="Image url" value="https://picsum.photos/id/17/200/300" />
        <TextInput label="Image alt goes here" />
    </Stack>
</Flex>

解决方案

问题出在Mantine的Image组件默认未设置宽度,在Flex布局中会被挤压至宽度为0,需给Image指定宽度或flex属性控制尺寸,同时适配容器高度:

方案1:设置固定宽度

给Image添加w属性指定宽度,用h="100%"让图片高度自适应输入框总高度,配合objectFit="contain"保证图片比例:

<Flex gap="md" align="stretch">
    <Image 
        src="https://picsum.photos/id/17/200/300" 
        w={80} 
        h="100%" 
        objectFit="contain" 
    />
    <Stack flex="1" gap="sm">
        <TextInput label="Image url" value="https://picsum.photos/id/17/200/300" />
        <TextInput label="Image alt" placeholder="Image alt goes here" />
    </Stack>
</Flex>

方案2:按比例分配宽度

给Image添加flex属性设置宽度比例,同时用minW防止被过度挤压:

<Flex gap="md" align="stretch">
    <Image 
        src="https://picsum.photos/id/17/200/300" 
        flex="0 0 20%" 
        minW={60}
        h="100%" 
        objectFit="contain" 
    />
    <Stack flex="1" gap="sm">
        <TextInput label="Image url" value="https://picsum.photos/id/17/200/300" />
        <TextInput label="Image alt" placeholder="Image alt goes here" />
    </Stack>
</Flex>

自适应容器高度说明

给Flex添加align="stretch"属性,让子元素高度撑满容器,不设置固定高度,容器会自动根据输入框总高度自适应。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:32:43