I want a HTML <table> to be just the size it needs to be.

Without specifying anything it will span the whole width. Setting width="auto" doesn't work.

有帮助吗?

解决方案

Do not set width on the table at all. This will make the table only as wide as needed by its content. If this looks too wide, look at the table content to see what causes width requirements in cells. For example, if you have long text in a cell, it will expand the cell to be as wide as needed, within the available width. If you wish to limit this, you need to set width or max-width on the content of a cell, or the cell itself, or the table.

其他提示

Use width: fit-content; for the table. See the difference below:

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>

You need to use CSS style instead of table attributes.

table
{
width:auto;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top