82

In the below HTML fragment, how can I make the width of a column that contains 'LAST' occupy the remainder of the row, and widths of columns that contain 'COLUMN ONE' and 'COLUMN TWO' be just wide enough to contain their content, and not larger.

Thank you

table {
  border-collapse: collapse;
}
table td {
  border: 1px solid black;
}
<table>
  <tr>
    <td>
      <table width="100%">
        <tr>
          <td>
            <span>
             COLUMN
           </span>
            <span>
             ONE
           </span>
          </td>
          <td>
            COLUMN TWO
          </td>
          <td>
            LAST
          </td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td>
      ANOTHER ROW
    </td>
  </tr>

</table>
userlond
  • 3,632
  • 2
  • 36
  • 53
ikaushan
  • 1,827
  • 3
  • 17
  • 20

1 Answers1

119

You will need to tell the first two columns not to wrap and give the last column a width of 99%:

<table width="100%">
       <tr>
         <td style="white-space: nowrap;">
           <span>
             COLUMN
           </span>
           <span>
             ONE
           </span>
         </td>
         <td style="white-space: nowrap;">
            COLUMN TWO
         </td>
         <td width="99%">
           LAST
         </td>
       </tr>
     </table>

Edit: You should put that all styles / presentation in (external...) css.

Using classes for the columns (you could use css3 selectors like nth-child() instead if you only target modern browsers):

html:

<tr>
  <td class="col1">
  // etc

css:

.col1, .col2 {
  white-space: nowrap;
}
.col3 {
  width: 99%;
}
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • 1
    The deprecation is for the tag, but if you are doing responsive / CSS tables using div and display:table-cell this works great. – ckaufman Apr 08 '13 at 18:23
  • 12
    @ckaufman Tables are not deprecated, a lot of the attributes are (`width`, `nowrap`, etc.). – jeroen Apr 08 '13 at 20:18
  • 2
    This works, but I had to also add a `min-width` attribute to the second column of my table to avoid it to shrink. – Ulysses Alves Jan 29 '16 at 18:22
  • What if there is a dropdown menu contained within the last table cell, that I would like to be the same width as the table cell it is in. Setting the width of the dropdown menu to 100% doesn't seem to work since the containing element's width is set to 99%. Is there any easy way to do this? Currently, I'm resorting to javascript to set width dynamically when the dropdown is opened. – flyingL123 Jun 08 '16 at 02:10
  • @flyingL123 knowing the parent width is 99% of what you need, you can set to 101% (99 + 0.09 = 99.9%) or a little bigger if needed. – Randy Hall Mar 09 '20 at 16:01