简体   繁体   中英

CSS calc not working for <td> width

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>

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.

I found a solution, but my solution requires client side scripting that functions after the document object loads (this should work for all browsers:)

<!DOCTYPE html>
<head>
<style type="text/css">
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);*/
}
</style>

<script type="text/javascript">
function init() 
{
EvalStatement = "document.getElementById(\"ColA\").setAttribute(\"width\", \"" + (document.getElementById("tableid").offsetWidth - 100) + "px;\")";
eval(EvalStatement);
}
</script>   

</head>

<body onresize="init();" onload="init();">
<table id="tableid">
<tbody>
<tr>
<td id="ColA">Cell A</td>
<td>Cell B</td>
<td>Cell C</td>
</tr>
</tbody>
</table>
</body>

 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% / 6 * 3.5); }
 <table> <tbody> <tr> <td>Cell A</td> <td>Cell B</td> <td>Cell C</td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM