6

I am trying to use calc to fix the width of my th:last-child which differs from the others by 15px. What I've done is:

th:last-child {
   width: calc( (100% - 30px)/12 + 30px );
}
table, tr {
width:100%;
border: 1px solid black;
height:10px;
}
th {
  border-right: 1px solid black;
  width: calc( (100% - 30px)/12 );
}
<table>
<thead>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
    <th>Column 4</th>
    <th>Column 5</th>
    <th>Column 6</th>
    <th>Column 7</th>
    <th>Column 8</th>
    <th>Column 9</th>
    <th>Column 10</th>
    <th>Column 11</th>
    <th>Column 12</th>
  </tr>
</thead>
<tbody>
 <tr>
    <td>Row 1</td>
    <td>Row 2</td>
    <td>Row 3</td>
    <td>Row 4</td>
    <td>Row 5</td>
    <td>Row 6</td>
    <td>Row 7</td>
    <td>Row 8</td>
    <td>Row 9</td>
    <td>Row 10</td>
    <td>Row 11</td>
    <td>Row 12</td>
 </tr>
  
 </tbody>
 </table>

JS Fiddle reproduction.

I've divided by 12 because it is the number of columns in my table. As I understood 100% is treated as the width of the parent. The problem is that finally, I don't get what I would expect, any idea why?

dippas
  • 58,591
  • 15
  • 114
  • 126

4 Answers4

4

You must set table-layout property to 'fixed'.

See using calc() with tables

And working example: https://jsfiddle.net/rpyydd5n/3/

Community
  • 1
  • 1
Paweł Adamski
  • 3,285
  • 2
  • 28
  • 48
0

Basically, you're setting the table to a width of 100% + 15px. So unless the parent element allows for that, most browsers will recalculate back to 100% and scale the TH's and TD's accordingly. Why not use min-width on the last child?

dippas
  • 58,591
  • 15
  • 114
  • 126
Jelle
  • 1
  • 1
0

change this in css

th:last-child {
       width: calc( 100%/12 + 100px );
       background-color:#ccc;

 }
th{width:5%; }
usman khan
  • 119
  • 5
0

What about using a padding-right of 15px on the last th to expand it, then using a div inside that th with a tricky width calc(100% + 15px), it doesn't give 1/12 of the table width + 15px, it gives instead the natural width of that last th content + 15px, which is not exactly what you are requiring.

The reason why I posted this right away is just to share an idea than can be useful to solve the problem:

table, tr {
    width:100%;
    border: 1px solid black;
    height:10px;
}

th {
  border-right: 1px solid black;
}

th:last-child {
  padding-right: 15px;
}

th:last-child > div {
  width: calc(100% + 15px);
}
<table>
<thead>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
    <th>Column 4</th>
    <th>Column 5</th>
    <th>Column 6</th>
    <th>Column 7</th>
    <th>Column 8</th>
    <th>Column 9</th>
    <th>Column 10</th>
    <th>Column 11</th>
    <th>
      <div>Column 12</div>
    </th>
  </tr>
</thead>
</table>
Daniel
  • 687
  • 4
  • 10