HTML table last td to take remaining width

前端 未结 2 1346
失恋的感觉
失恋的感觉 2021-01-14 03:29

I have a table with one TR and 2 TD\'s. I want the first TD to adjust width automatically depending on its content, and the second TD to use up the remainder of the width.

相关标签:
2条回答
  • 2021-01-14 03:41

    You can give the first td a small width, e.g. 1px, with white-space: nowrap;

    table {
      width: 100%;
      border-collapse: collapse;
    }
    td {
      border: 1px solid red;
    }
    td:first-child {
      width: 1px;
      white-space: nowrap;
    }
    <table>
      <tr>
        <td>short content</td>
        <td>long content</td>
      </tr>
    </table>

    Or, give the last td a large width, e.g. 100%.

    table {
      width: 100%;
      border-collapse: collapse;
    }
    td {
      border: 1px solid red;
    }
    td:first-child {
      white-space: nowrap;
    }
    td:last-child {
      width: 100%;
    }
    <table>
      <tr>
        <td>short content</td>
        <td>long content</td>
      </tr>
    </table>

    0 讨论(0)
  • 2021-01-14 03:49

    Setting white-space: nowrap on all cells except for the last one, and giving the last one 100% width, worked for me:

        td:not(:last-child), th:not(:last-child) {
          white-space: nowrap;
        }
    
        td:last-child, th:last-child {
          width: 100%;
        }
    

    This will make sure that text wrapping still works while still filling the table when space is available.

    0 讨论(0)
提交回复
热议问题