Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top