CSS calc不适用于宽度

时间:2017-12-07 03:02:19

标签: html css

我希望 Cell A 为剩下的两个单元留下100px。我认为calc(100% - 100px)就足够了,因为在许多其他情况下这种方法效果很好。为什么不在这里工作?



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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

至少在Chrome中,在colgroup元素上定义宽度似乎有效:

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>

答案 1 :(得分:-2)

我找到了一个解决方案,但我的解决方案需要在文档对象加载后运行的客户端脚本(这应适用于所有浏览器:)

<!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>

答案 2 :(得分:-3)

&#13;
&#13;
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);
}
&#13;
<table>
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;