Home > Mobile >  Expand last table column to fill container
Expand last table column to fill container

Time:08-14

How do you expand the last column of a table to fill the parent container without specifying a width for the container? In this jsfiddle, I want the last column of the green table to fill the blue container. The width of the container should only be determined by its text.

.container{
  background-color: #003388;
  color: white;
  display: inline-block;
}

table {
  background-color: #008833;
  color: white;
  width:auto;
}

table tr td:last-child {
  /* width:100%; */
}

Setting the width of the last td fills the entire page.

CodePudding user response:

One possible approach is given below. It uses...

  • width: 100% rule (instead of width: auto) to make table fill the container

  • width: 1px; white-space: nowrap; combo trick to make all the columns define their width based on content width; without that rule it seems there's no simple way to override default behaviour of table-layout: auto sharing the whole width between columns equally.

  • max-width: 1px for the last column to ensure that inline-block container is not extended when that column grows, and text is wrapped instead

.container{
    background-color: #003388;
    color: white;
    display: inline-block;
}

table {
    background-color: #008833;
    color: white;
    width: 100%;
}

table td:not(:last-child) {
    width: 1px;
    white-space: nowrap;
}

table td:last-child {
   max-width: 1px; 
}
<div >
long text long text long text long text long text long text

<table>
    <tr>
        <th>Product</th>
        <th>Cardinality</th>
        <th>Price per item</th>
    </tr>
    <tr>
        <td>Apple</td>
        <td>5</td>
        <td>$2</td>
    </tr>
    <tr>
        <td>Pear</td>
        <td>3</td>
        <td>$3</td>
    </tr>
    <tr>
        <td>Sausage</td>
        <td>10</td>
        <td>$0.5</td>
    </tr>
    <tr>
        <td>Pineapple</td>
        <td>2</td>
        <td>$8</td>
    </tr>
    <tr>
        <td>Tomato</td>
        <td>5</td>
        <td>$1</td>
    </tr>
    <tr>
        <td>Lightsaber</td>
        <td>2</td>
        <td>$99 999 999999999 99999999 99999999</td>
    </tr>
</table>

</div>

CodePudding user response:

Use fractional units fr to automatically take up the fraction you desire

  • Related