user2837732
user2837732

Reputation:

Table should be only as wide as necessary

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.

Upvotes: 3

Views: 3985

Answers (3)

Joel Grayson
Joel Grayson

Reputation: 197

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>

Upvotes: 3

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201668

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.

Upvotes: 3

Yuk Ming Chik
Yuk Ming Chik

Reputation: 9

You need to use CSS style instead of table attributes.

table
{
width:auto;
}

Upvotes: -1

Related Questions