Search code examples
htmlcsscellcss-tables

Flexible table according to a cell size


I have tables like this:

   ------------------------------------------------
  |   product-name                   | icon | text |
   ------------------------------------------------
  |   product-info                   | icon | text |
   ------------------------------------------------

I want my cells to be flexible according to the last cell content:

   ------------------------------------------------
  |   product-name                      | ic | smt |
   ------------------------------------------------
  |   product-info                      | ic | smt |
   ------------------------------------------------

   -------------------------------------------------
  |   product-name                | icon | big-text |
   -------------------------------------------------
  |   product-info, bla bla bla...| icon | text     |
   -------------------------------------------------

I tried this css:

  table {
    table-layout: fixed;
    font-size: 12px;
    width: 100%;
  }

  table td:nth-child(1) {
    max-width: 70%;
  }

  table td:nth-child(2) {
    width: 10%;
  }

  table td:nth-child(3) {
    max-width: 20%;
  }

I put table-layout:fixed, but I can't manage to make the max-width to work. And I don't know how to tell that the last cell is the one to determine the others size.

The product-info content can be very big and I applied an ellipsis it become too large.


Solution

  • The first thing to do is get rid of table-layout: fixed, because that does the opposite of what you want. For the rest, if you want tables to be flexible, don't try to force widths on them!

    There's a little trick to make some table cells as wide as their content, while giving the remaining cells the rest of the remaining space: make their width 1px and make sure that they can't wrap by setting white-space: nowrap. Then the rest will come naturally.

    table {
      border: 1px outset;
      width: 100%;
    }
    
    th, td {
      border: 1px inset;
    }
    
    table td:nth-child(2),
    table td:nth-child(3) {
      white-space:nowrap;
      width: 1px;
    }
    <table>
      <tr>
        <td>product-name</td>
        <td>ic</td>
        <td>smt</td>
      </tr>
      <tr>
        <td>product-info</td>
        <td>ic</td>
        <td>smt</td>
      </tr>
    </table>
    <br>
    <table>
      <tr>
        <td>product-name</td>
        <td>icon</td>
        <td>big-text</td>
      </tr>
      <tr>
        <td>product-info, bla bla bla...</td>
        <td>ic</td>
        <td>smt</td>
      </tr>
    </table>

    Hope this is what you meant!