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

无法设置表格<td>元素宽度的技术问题咨询

解决表格<td>宽度无法设置的问题

问题出在你把table-layout: fixed属性加在了<td>和<th>上——这个CSS属性是专门给<table>元素设置的,用来强制表格按照指定列宽布局,不会因单元格内容自动调整宽度。

修复步骤:

  • 将table-layout: fixed从.custom-table td, .custom-table th的样式中移除,加到.custom-table的样式定义里
  • 给表格添加明确宽度(比如width: 100%),确保table-layout: fixed能正常生效

修改后的完整代码:

<template>
  <div class="card">
    <table class="table table-hover custom-table table-responsive">
      <thead>
        <draggable v-model="tableHeaders" :options="{ handle: '.handle' }">
          <th class="handle" v-for="header in tableHeaders" :key="header">
            {{ header }}
          </th>
        </draggable>
      </thead>
      <tbody>
        <draggable
          v-model="tableData"
          :options="{
            handle: '.handle',
            ghostClass: 'ghost-class',
            chosenClass: 'chosen-class',
          }"
        >
          <tr v-for="item in tableData" :key="item.id" class="handle">
            <td v-for="header in tableHeaders">
              {{ item[header.toLowerCase()] }}
            </td>
          </tr>
        </draggable>
      </tbody>
    </table>
  </div>
</template>

<style>
th:hover,
td:hover {
  cursor: pointer;
}
.ghost-class {
  opacity: 0.5;
  z-index: 9999;
  transition: all 0.3s ease-in-out;
}

.chosen-class {
  opacity: 0.5;
  transition: all 0.3s ease-in-out;
}

/* 核心修改:把表格布局属性移到table元素上 */
.custom-table {
  table-layout: fixed;
  width: 100%;
}

.custom-table td,
.custom-table th {
  transition: all 0.3s ease-in-out;
  text-align: center;
  vertical-align: middle;
  font-size: 13px;
  border: 1px solid red;
  width: 5%;
}

.custom-table .handle {
  cursor: move;
}

.custom-table .handle:active {
  cursor: grabbing;
}

.custom-table .handle:hover {
  background-color: #323346;
  color: #ffffff;
}

.custom-table .handle:hover td,
.custom-table .handle:hover th {
  opacity: 0.6;
}

.custom-table .handle:hover .chosen-class,
.custom-table .handle:hover .ghost-class {
  opacity: 0.6;
}

.custom-table .handle:hover .chosen-class {
  cursor: grabbing;
}

.custom-table .handle:hover .ghost-class {
  cursor: move;
}
</style>

额外提示:

如果单元格内有超长文本,可能仍会撑宽单元格,可以给<td>和<th>添加word-break: break-all,或者overflow: hidden; text-overflow: ellipsis; white-space: nowrap来限制内容显示,保证列宽稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:23:12