【问题标题】:Table should be only as wide as necessary表应仅根据需要宽
【发布时间】:2022-01-17 00:42:02
【问题描述】:

我希望 HTML <table> 正好是它需要的大小。

如果不指定任何内容,它将跨越整个宽度。设置width="auto" 不起作用。

【问题讨论】:

标签: html width html-table autosize


【解决方案1】:

根本不要在桌子上设置宽度。这将使表格仅根据其内容的需要而变宽。如果这看起来太宽,请查看表格内容以了解导致单元格宽度要求的原因。例如,如果单元格中有长文本,它将在可用宽度内将单元格扩展为所需的宽度。如果您希望对此进行限制,则需要在单元格的内容、单元格本身或表格上设置widthmax-width

【讨论】:

  • 我已将宽度设置为空,它跨越了整个页面。任何单元格内都没有换行文本。
  • 然后你需要发布相关代码(理想情况下,最少的代码足以重现问题,但无论如何一些代码,或至少一个URL)。如果你用<table border><tr><td>foo</table>测试,你可以看到它并没有跨越整个页面。
  • 我的错。一直有换行。
【解决方案2】:

对表格使用width: fit-content;。看看下面的区别:

table, tr, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

.container {
  width: 300px;
  border: 1px solid red;
  display: flex;
  flex-direction: column;
}

table#fit-content {
  width: fit-content;
}
<div class='container'>
  <button>Regular</button>
  <table>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
        <tr>
        <td>4</td>
        <td>3</td>
      </tr>
    </tbody>
  </table>
</div>
<br>
<div class='container'>
  <button>With Fit-Content</button>
  <table id='fit-content'>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
        <tr>
        <td>4</td>
        <td>3</td>
      </tr>
    </tbody>
  </table>
</div>

【讨论】:

    【解决方案3】:

    您需要使用 CSS 样式而不是表格属性。

    table
    {
    width:auto;
    }
    

    【讨论】:

    • 不需要,也无济于事; width: auto 是默认值。
    猜你喜欢
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多