【问题标题】:How to distribute free space between <table> columns evenly?如何在 <table> 列之间平均分配可用空间?
【发布时间】:2021-12-14 12:21:17
【问题描述】:

我想让我的 html 表格以th 元素内容不重叠的方式占据整个窗口宽度 + 列标题之间甚至有间距(见图)。 空间必须随着窗口宽度最大为 0 缩放(所有单词都相互拥抱)。怎么做?

大屏示例:

小屏示例:

默认情况下,th 元素之间的间距与元素的宽度成正比。

如果我使用table-layout: fixed,列的宽度将相等,即它们之间的空间与宽度不成比例。

附:我需要使用border-spacing: 0,因为我需要突出显示完整的表格行,并且正面border-spacing 表格背景将在单元格之间可见。 附言这个问题专门关于表格布局。我知道我可以用网格和弹性框做任何事情,但我正在尝试为正确的内容使用正确的标签,在这种情况下我有一个表格数据,即解决方案应该与“显示:表格”一起使用。

table {
  width: 80%;
  background: gray;
}

th {
  text-align: left;
}

.auto {
  background: #90EE90;
}

.fixed {
    table-layout: fixed;
  background: #ADD8E6;
}
<table class="auto">
<thead>
<tr>
<th>1</th>
<th>333</th>
<th>999999999</th>
<th>22</th>
</tr>
</thead>
<tbody>
<tr>
<td>aa</td>
<td>aa</td>
<td>aa</td>
<td>aa</td>
</tr>
</tbody>
</table>

<table class="fixed">
<thead>
<tr>
<th>1</th>
<th>333</th>
<th>999999999</th>
<th>22</th>
</tr>
</thead>
<tbody>
<tr>
<td>aa</td>
<td>aa</td>
<td>aa</td>
<td>aa</td>
</tr>
</tbody>
</table>

【问题讨论】:

  • th {width: 25%;} ?
  • 要真正了解您的目标到底是什么,在这种情况下,一张图片可能会有所帮助
  • @A.Meshu,我无法想象它会起作用。它与单词之间的空格有什么关系?
  • @klm123 你能添加一张想要的结果的图片吗?
  • @Corrl 根据引导文档Gutters can be responsively adjusted. Use breakpoint-specific gutter classes to modify horizontal gutters, vertical gutters, and all gutters.Gutters - Bootstrap v5.0

标签: html css html-table


【解决方案1】:

一个可能有点 hacky 的唯一 css 解决方案是插入空的 th/td 元素并为它们提供 100% 的实际宽度/填充列的数量。这里有 4 列 -> 间隙宽度:25%(如果是奇数则使用 calc())

table {
  width: 80%;
  border-spacing: 0
}
th {
  text-align: left;
}
th,
td {  
  border: 1px solid teal;
}

.gap {
  width: 25%;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>

  <table>
    <thead>
      <tr>
        <th>1</th>
        <th class="gap"></th>
        <th>333</th>
        <th class="gap"></th>
        <th>999999999</th>
        <th class="gap"></th>
        <th>22</th>
        <th class="gap"></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>aa</td>
        <td class="gap"></td>
        <td>aa</td>
        <td class="gap"></td>
        <td>aa</td>
        <td class="gap"></td>
        <td>aa</td>        
        <td class="gap"></td>
      </tr>
    </tbody>
  </table>

</body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多