Fixed Thead; Scrollable Tbody ~ Righter Columns Less Aligned

时间:2019-02-18 00:47:46

标签: html css html-table flexbox

After reading many posts about having a fixed theader with a scrollabe tbody, most answers point to adjusting the tbody to display: block. However, display block makes my columns on the righter side have a skewed alignment the further right the column goes. I am dealing with dynamic data so sometimes my table is rendered with 16 columns, but sometimes it could be up to 25 columns. I want all the columns aligned properly, while maintaining a fixed thead with a scrollable tbody. Here is my CSS:

table {
  overflow: hidden;
  width: 100%;
  height: 810px;
  table-layout: fixed;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden;
}

thead,
tbody {
  width: 100%;
}

tbody {
  flex: 1;
  overflow-y: scroll;
  width: 100%;
}

th {
  cursor: pointer;
}

th {
}

td {
  display: flex;
  justify-content: center;
}

td,
th {
  padding: 0;
}

tr {
  width: 100%;
  display: flex;
}

tr th {
  flex: 1;
}

tr td {
  flex: 1;
}

Here is a small Codepen example: https://codepen.io/anon/pen/xMmqxK

The Codepen skew is less prominent than the skew on my website, so it's a bit hard to notice. Any help would be much appreciated. If I posted a screenshot you would be able to see the problem more, however, I cannot due to a corporate envrionment. Thanks again.

1 个答案:

答案 0 :(得分:0)

这里的主要问题是<th>text-align:center,而<td>text-align:left。这就是为什么每列有更多空间时偏斜会增加的原因。

最简单的解决方案是从padding-left: 10px中删除<tbody> (仅包含在CopePen中)并将<td>设置为text-align: center

>

如果您需要将<td>左对齐,则可以进行相反的操作,并将<th>设置为text-align:left

相关问题