具有固定布局100%宽度的表不等列宽度

  • 本文关键字:布局 100% html css html-table
  • 更新时间 :
  • 英文 :


i有一个表设置为100%宽度,我想获取定义的宽度。但是,我所有的列似乎都获得了相等的宽度。

.table {
  table-layout: fixed;
  width: 100%;
}
.table th[colspan=4] {
  /* width: 100%; */
}
.table td,
th {
  border: 1px solid #AAA;
  text-align: center;
}
.table td.one {
  width: 10%;
}
.table td.two {
  width: 20%;
}
.table td.three {
  width: 50%;
}
.table td.four {
  width: 20%;
}
<table class="table">
  <tbody>
    <tr>
      <th colspan="4">All Four</th>
    </tr>
    <tr>
      <th colspan="4">All Four</th>
    </tr>
    <tr>
      <td class="one">A</td>
      <td class="two">B</td>
      <td class="three">C</td>
      <td class="four">D</td>
    </tr>
  </tbody>
</table>

如果我删除了表上的宽度属性,它将尊重单个列宽度。如果我将布局更改为table-layout: auto,则它也可以使用。但是,如果我有一排将多个列跨为第一行,我只是无法使宽度成为我想要的。

如果我删除了桌子上的宽度属性,它会尊重个人 列宽。如果我将布局更改为table-layout:auto,则 有用。但是我只是无法使宽度成为我想要的 如果我有一排将多列作为第一行

这就是table-layout: fixed的工作方式。

从这里:https://developer.mozilla.org/en-us/docs/web/css/table-layout

表和列宽度由表和col的宽度设置 元素或第一行宽度。细胞中的 随后的行不影响列宽度。

和此处:https://www.w3.org/tr/css21/tables.html#fixed-table-layout

以这种方式,用户代理可以在 已经收到了整个第一行。随后的行中的单元不 影响色谱柱宽度。

所以,实际上:

  1. 如果将布局更改为auto,它将使用自动表布局,并且列宽度优先于内容大小。
  2. 如果您删除了表上的width属性,则它停止使用固定的表布局,并且与auto一样好。

另一个答案起作用,因为删除了width属性(就像您在问题中提到的那样)。如果您参考上面链接的规格,则说:

可以用"宽度"明确指定表的宽度 财产。"自动"的值(既适用'display:table'和'显示: 内联桌')表示使用自动表布局算法。

解决方案

解决问题的解决方案是以某种方式获取表布局以忽略第一行。这是由colgroup/col元素完成的。删除定义td上宽度的类,并在cols上指定这些类别。

代码

.table { table-layout: fixed; width: 100%; }
.table td, th {
  border: 1px solid #aaa; 
  text-align: center; padding: 4px;
}
.table col.one { width: 10%; }
.table col.two { width: 20%; }
.table col.three { width: 50%; }
.table col.four { width: 20%; }
<table class="table">
	<colgroup>
		<col class="one"/>
		<col class="two"/>
		<col class="three"/>
		<col class="four"/>
	</colgroup>
  <tbody>
    <tr><th colspan="4">All Four</th></tr>
    <tr><th colspan="4">All Four</th></tr>
    <tr>
      <td >A</td>
      <td >B</td>
      <td >C</td>
      <td >D</td>
    </tr>
  </tbody>
</table>

说实话,我不能完全告诉你"为什么"。但是,如果将width: 100%;更改为min-width: 100%,则会获得所需的结果。我想这是因为如果将宽度设置为100%,则无法计算每列的总宽度。

.table {
  table-layout: fixed;
  min-width: 100%;
}
.table th[colspan=4] {
  /* width: 100%; */
}
.table td,
th {
  border: 1px solid #AAA;
  text-align: center;
}
.table td.one {
  width: 10%;
}
.table td.two {
  width: 20%;
}
.table td.three {
  width: 50%;
}
.table td.four {
  width: 20%;
}
<table class="table">
  <tbody>
    <tr>
      <th colspan="4">All Four</th>
    </tr>
    <tr>
      <th colspan="4">All Four</th>
    </tr>
    <tr>
      <td class="one">A</td>
      <td class="two">B</td>
      <td class="three">C</td>
      <td class="four">D</td>
    </tr>
  </tbody>
</table>

最新更新