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

如何在React.js+Tailwind CSS中实现嵌套于Outlet的响应式表格

修复Tailwind CSS响应式表格横向滚动问题

针对你的情况,给表格添加min-w-full类即可解决溢出问题,同时可优化移动端内边距提升体验,修改后的Table.jsx代码如下:

return (
  <>
    <div className="bg-white p-4 rounded-lg shadow-[0_1px_2px_rgba(3,18,26,0.2)] mb-6 overflow-x-auto">
      {/* 给table添加min-w-full,确保表格宽度适配容器 */}
      <table className="min-w-full">
        <thead className="border-b border-b-[#f0f3f3]">
          <tr className="text-sm text-[#8f8f8f]">
            {/* 用响应式类缩小移动端内边距 */}
            <th className="px-2 sm:px-3 py-2 text-left">Nama</th>
            <th className="px-2 sm:px-3 py-2 text-left">Mengajar</th>
            <th className="px-2 sm:px-3 py-2 text-left">Telepon</th>
            <th className="px-2 sm:px-3 py-2 text-left">Gender</th>
            <th className="px-2 sm:px-3 py-2 text-left">Email</th>
            <th className="px-2 sm:px-3 py-2 text-left">Alamat</th>
            <th className="px-2 sm:px-3 py-2 text-right">Dibuat Pada</th>
          </tr>
        </thead>
        <tbody>
          {getTeachers.map((teacher, i) => (
            <tr key={i}>
              <td className="px-2 sm:px-3 py-2">
                <div className="cursor-pointer flex items-center gap-2 max-w-[300px]">
                  <Avatar variant="rounded" alt={teacher.name} src={teacher.picture} sx={{ bgcolor: 'white' }} />
                  <span className="truncate">{teacher.name}</span>
                </div>
              </td>
              <td className="px-2 sm:px-3 py-2 text-left">{teacher.subject}</td>
              <td className="px-2 sm:px-3 py-2 bg-red-200">{teacher.phone}</td>
              <td className="px-2 sm:px-3 py-2">{teacher.gender}</td>
              <td className="px-2 sm:px-3 py-2">{teacher.email}</td>
              <td className="px-2 sm:px-3 py-2">{teacher.address}</td>
              <td className="px-2 sm:px-3 py-2 bg-red-200 text-right">{teacher.registered}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </>
);

关键修改说明:

  • min-w-full 给table:默认情况下table宽度由内容决定,不会主动撑满容器,添加该类后表格会填充外层容器宽度,当内容超出容器时,外层的overflow-x-auto会触发横向滚动。
  • 响应式内边距:用px-2 sm:px-3在移动端缩小单元格左右内边距,避免内容过度拥挤。
  • 移除thead中的mb-4:thead属于表格内部元素,margin属性不会生效,属于无效样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:35:08