如何创建具有固定/冻结左列和可滚动正文的 HTML 表格?

2022-01-30 00:00:00 html-table html css

我需要一个简单的解决方案.我知道这与其他一些问题类似,例如:

I need a simple solution. I know it's similar to some other questions, like:

  • 具有固定标题和固定列的 HTML 表格?
  • 如何在滚动时锁定表格的第一行和第一列,可能使用 JavaScript 和 CSS?

但我只需要冻结一个左列,我更喜欢简单且无脚本的解决方案.

But I need just a single left column to be frozen and I would prefer a simple and script-less solution.

推荐答案

如果你想要一个只有列水平滚动的表格,你可以 position: absolute 第一列(并明确指定它的宽度),然后将整个表格包装在 overflow-x:scroll 块中.但是,不要费心在 IE7 中尝试这个...

If you want a table where only the columns scroll horizontally, you can position: absolute the first column (and specify its width explicitly), and then wrap the entire table in an overflow-x: scroll block. Don't bother trying this in IE7, however...

相关 HTML &CSS:

Relevant HTML & CSS:

table {
  border-collapse: separate;
  border-spacing: 0;
  border-top: 1px solid grey;
}

td, th {
  margin: 0;
  border: 1px solid grey;
  white-space: nowrap;
  border-top-width: 0px;
}

div {
  width: 500px;
  overflow-x: scroll;
  margin-left: 5em;
  overflow-y: visible;
  padding: 0;
}

.headcol {
  position: absolute;
  width: 5em;
  left: 0;
  top: auto;
  border-top-width: 1px;
  /*only relevant for first row*/
  margin-top: -1px;
  /*compensate for top border*/
}

.headcol:before {
  content: 'Row ';
}

.long {
  background: yellow;
  letter-spacing: 1em;
}

<div>
<table>
        <tr><th class="headcol">1</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>
        <tr><th class="headcol">2</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>
        <tr><th class="headcol">3</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>
        <tr><th class="headcol">4</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>
        <tr><th class="headcol">5</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>
        <tr><th class="headcol">6</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>
</table>
</div>

小提琴

相关文章