首页 > 解决方案 > Fixed Thead; Scrollable Tbody ~ Righter Columns Less Aligned

问题描述

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.

标签: htmlcsshtml-tableflexbox

解决方案


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

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

如果你需要左对齐<td>的 s 那么你可以做相反的事情并将你<th>的 s 设置为text-align:left


推荐阅读