Tailwind overflow-x失效:横向列表无法滚动仅缩小元素
解决横向列表滚动时元素被压缩的问题
核心修复要点
- 给父容器添加
flex overflow-x-auto,开启弹性布局并允许横向滚动 - 给每个子div添加
flex-shrink-0,强制子元素保持自身宽度,不被压缩 - 可选:给父容器加
py-2增加垂直内边距,避免滚动条和内容贴紧
修复后的示例代码
<div class="flex overflow-x-auto py-2"> <div class="flex-shrink-0 w-48 h-24 bg-blue-500 mx-2"></div> <div class="flex-shrink-0 w-48 h-24 bg-green-500 mx-2"></div> <div class="flex-shrink-0 w-48 h-24 bg-red-500 mx-2"></div> <div class="flex-shrink-0 w-48 h-24 bg-yellow-500 mx-2"></div> <div class="flex-shrink-0 w-48 h-24 bg-purple-500 mx-2"></div> </div>
原理说明
overflow-x-auto:当容器内容总宽度超过容器自身宽度时,自动触发横向滚动条flex-shrink-0:默认flex子元素的flex-shrink值为1,空间不足时会自动缩小;设置为0后,子元素会固定保持定义的宽度- 默认的
flex-nowrap(flex布局默认属性):确保子元素在单行排列,不会换行
内容的提问来源于stack exchange,提问作者rameez khan
相关产品推荐
相关产品推荐

