React+Tailwind中动态内容Div无法滚动,卡片自动缩容问题
问题解决方法
问题根源在于flex布局默认会让子元素自动收缩以适配容器宽度,导致卡片被挤压而非触发横向滚动。只需做两处关键修改:
1. 修改AppointmentsList的卡片容器
给承载卡片的flex容器添加flex-nowrap类,强制子元素保持在一行,避免自动收缩或换行:
export default function AppointmentList({ appointments }) { return( <div className="w-full h-auto flex flex-col font-sans"> <div className="flex flex-row justify-between items-center"> <h2 className="text-2xl text-gray-500">Incoming Appointments</h2> <span className="text-xl text-gray-400">5 Pending Approval</span> </div> {/* 添加flex-nowrap,配合overflow-x-auto实现横向滚动 */} <div className="w-full h-auto bg-black flex gap-3 overflow-x-auto flex-nowrap"> {appointments.map((appointment) => { return <AppointmentListCard appointment={appointment} key={"appointment_" + appointment.id}/> })} </div> </div> ) }
2. 给卡片添加防收缩保障
为了彻底避免卡片被压缩,给AppointmentListCard添加flex-shrink-0类,强制固定宽度:
export default function AppointmentListCard({ appointment }) { return( <div className="h-52 w-52 flex-shrink-0 rounded-md bg-slate-400 p-5 flex flex-col justify-center"> <div className="flex flex-row gap-3 "> <span>Patient Name: </span> <span className="text-gray-400">{appointment.patient?.name}</span> </div> </div> ) }
核心原理
flex-nowrap:阻止flex容器内的子元素换行或自动收缩,保持横向排列flex-shrink-0:强制卡片不参与flex收缩逻辑,严格维持设置的宽度overflow-x-auto:当卡片总宽度超出容器时,自动显示横向滚动条
修改完成后,卡片数量超出容器宽度时会触发横向滚动,不再自动缩小尺寸。
内容的提问来源于stack exchange,提问作者Safwan Parkar
相关产品推荐
相关产品推荐

