浏览器忽略表格布局:已修复

时间:2015-02-01 19:23:01

标签: html css html-table

我无法实现固定的表格布局。如果表格单元格的内容多于容纳在其中的内容,则表格将被转发,就像表格布局设置为自动一样。 这是HTML代码

<!DOCTYPE html>
<html>
  <head>
    <title>Table test</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" type="text/css" href="<path here>" /> 
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th class="number">Number</th>
          <th class="name">Name</th>
          <th class="type">Type</th>
          <th class="comment">Comment</th>
          <th class="buttons"></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>42</td>
          <td>This name is really long and is supposed to be truncated</td>
          <td>Normal</td>
          <td>I don't know what to say</td>
          <td><button>Edit...</button></td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

CSS

table {
  border-collapse: collapse;
  table-layout: fixed;
}

th {
  font-weight: bold;
  text-align: left;
}

td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

tr {
  border-top: 1px solid #000000;
  border-bottom: 1px solid #000000;
}

th.number {
  width: 6rem;
}

th.name {
  width: 15rem;
}

th.type {
  width: 17rem;
}

th.comment {
  width: 15rem;
}

th.buttons {
  width: 17rem;
}

这是fiddle。问题是第二列(“名称”)增加,直到内容适合。我做错了什么?

1 个答案:

答案 0 :(得分:2)

您需要在width元素上设置table,因为Fixed table layout的定义是:“表格的宽度可以使用&#39;明确指定。宽度&#39;属性。值为&#39; auto&#39; (对于&quot; display:table&#39;和&#39; display:inline-table&#39;)表示使用自动表格布局算法。但是,如果表是正常流程中的块级表(&#39; display:table&#39;),则UA可以(但不必)使用10.3.3的算法来计算宽度并应用固定表格布局,即使指定的宽度为&#39; auto&#39 ;.“(请注意,auto是默认值。)

这很尴尬,但要获得固定布局,您需要添加

table { width: calc(40rem + 10px); }

此处40rem是您为列设置的宽度的总和,10px适应单元格中的默认填充(每个单元格中左侧和右侧的1px)。

较旧的浏览器不支持calc构造,但您已使用rem单位冒险。