【问题标题】:Browser ignores table-layout:fixed浏览器忽略表格布局:已修复
【发布时间】:2015-02-02 03:46:53
【问题描述】:

我未能实现固定的表格布局。如果表格单元格包含的内容超出其容纳范围,则表格将重新布局,就像表格布局设置为自动一样。 这是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。问题是第二列(“名称”)会增加,直到内容适合。我做错了什么?

【问题讨论】:

    标签: html css html-table


    【解决方案1】:

    您需要在table 元素上设置width,因为Fixed table layout 的定义说:“表格的宽度可以通过'width' 属性显式指定。 'auto' 的值(对于 'display: table' 和 'display: inline-table')意味着使用自动表格布局算法。但是,如果表格是正常流程中的块级表格('display: table'),UA 可以(但不是必须)使用 10.3.3 的算法来计算宽度并应用固定表格布局,即使指定的宽度是'auto'。” (注意auto是默认值。)

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

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

    这里40rem 是您为列设置的宽度之和,10px 容纳单元格中的默认填充(1px 在每个单元格的左侧和右侧)。

    较旧的浏览器不支持calc 构造,但您已经在使用rem 单元承担风险。

    【讨论】:

    • 这就是我所担心的。我希望,如果所有列都有宽度,我可以避免明确设置总宽度。 (在这种情况下,总宽度将是多余的。)我上面的示例非常简化,因为每列的单独宽度要复杂得多,并且使用媒体查询。我希望浏览器足够智能,能够自行计算出总宽度。
    猜你喜欢
    • 2011-08-07
    • 2011-05-25
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多