如何让图片在TailwindCSS与ShadCN Dialog中适配容器并保持比例?
如何让ShadCN Dialog中的图片适配容器并保留宽高比?
我遇到了图片超出父容器边界的问题,相关TSX代码如下:
export function Dialog() { const src = 'https://placehold.co/1080x1920'; return ( <Dialog open={isOpen} onOpenChange={onClose}> <DialogContent className='flex max-h-[60%] min-h-[60%] max-w-[60%] min-w-[60%] flex-col bg-white'> <div className='flex grow gap-6'> {/* Left column */} <div className='flex flex-1 justify-center overflow-hidden rounded-lg bg-gray-200'> {src && <img className='max-h-full max-w-full rounded-lg' src={src} />} </div> {/* Right Column */} <div className='flex-1 space-y-4'> <div className='text-xl font-semibold'>Title</div> Some content </div> </div> </DialogContent> </Dialog> ); }
我希望图片能适配容器同时保留宽高比,试过组合使用object-contain、百分比高度(如h-[80%])和分数类高度(如h-3/4),但都没能解决问题。
更新1:整个组件是包裹在ShadCN Dialog中的,会不会是这个组件的默认样式导致的问题?
更新2:我通过他人建议解决了问题,方法是在DialogContent的className中添加!max-w-fit类。
方案说明
ShadCN Dialog的内容容器默认带有固定宽度限制,!max-w-fit可以强制容器宽度自适应内部内容,再配合图片上已有的max-h-full和max-w-full样式,就能让图片在不超出容器范围的前提下自动缩放,同时保留原有的宽高比。
内容的提问来源于stack exchange,提问作者francosang
相关产品推荐
相关产品推荐

