Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS calc not working for <td> width

Tags:

html

css

I'd like Cell A to leave exactly 100px for the remain two cells. I would think calc(100% - 100px) would be sufficient as this works just fine in many other situations. Why isn't it working here?

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

td:first-child {
  width: calc(100% - 100px);
}
<table>
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table>
like image 832
Eaten by a Grue Avatar asked Dec 07 '17 03:12

Eaten by a Grue


People also ask

How do I fix td width in CSS?

By using CSS, the styling of HTML elements is easy to modify. To fix the width of td tag the nth-child CSS is used to set the property of specific columns(determined by the value of n) in each row of the table.

What does CALC () do in CSS?

calc() The calc() CSS function lets you perform calculations when specifying CSS property values. It can be used anywhere a <length> , <frequency> , <angle> , <time> , <percentage> , <number> , or <integer> is allowed.

How do you change the width of a TD table?

To set the cell width and height, use the CSS style. The height and width attribute of the <td> cell isn't supported in HTML5. Use the CSS property width and height to set the width and height of the cell respectively. Just keep in mind, the usage of style attribute overrides any style set globally.


1 Answers

At least in Chrome, it seems to work when defining the width on a colgroup element:

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

colgroup:first-child {
  width: calc(100% - 100px);
}
<table>
  <colgroup/>
  <colgroup span="2" />
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table>

Update April 1st, 2020

This no longer seems to work in the current version of Chrome. I'll leave the answer to serve as a test case should the behavior change in the future.

like image 175
Robby Cornelissen Avatar answered Oct 22 '22 12:10

Robby Cornelissen