固定表格标题和前两列

时间:2018-11-27 12:33:11

标签: css

我正在尝试使固定的表头和前两列固定。我在固定列时遇到了麻烦(向右滚动后,它们始终会显示) 我拥有的当前代码使表标题固定,并且工作良好,但是我需要固定列号和名称。表很大,标题中有很多列。

.tableFixHead {
  overflow-y: auto;
  height: 600px;
}

.tableFixHead table {
  border-collapse: collapse;
  width: 100%;
}

.tableFixHead th,
.tableFixHead td {
  padding: 8px 16px;
}

.tableFixHead th {
  position: sticky;
  top: 0;
  background: #eee;
}
<div class="tableFixHead">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>#</th>
        <th>Name</th>
        <th>01-11</th>
        <th>02-11</th>
        <th>03-11</th>
        <th>04-11</th>
        <th>05-11</th>
        <th>06-11</th>
        </th>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Jack</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Michel</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Amanda</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
      </tr>
    </tbody>
  </table>
</div>

1 个答案:

答案 0 :(得分:1)

.tableFixHead {
  overflow: auto;
  height: 100px;
  width:300px;
}

.tableFixHead table {
  border-collapse: collapse;
  width: 100%;
}

.tableFixHead th,
.tableFixHead td {
  padding: 8px 16px;
}


td:first-child, th:first-child {
  position:sticky;
  left:0;
  z-index:1;
  background-color:white;
}
td:nth-child(2),th:nth-child(2)  { 
position:sticky;
  left:40px;
  z-index:1;
  background-color:white;
  }
.tableFixHead th {
  position: sticky;
  top: 0;
  background: #eee;
  z-index:2
}
th:first-child , th:nth-child(2) {
  z-index:3
  }
<div class="tableFixHead">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>#</th>
        <th>Name</th>
        <th>01-11</th>
        <th>02-11</th>
        <th>03-11</th>
        <th>04-11</th>
        <th>05-11</th>
        <th>06-11</th>
        </th>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Jack</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Michel</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Amanda</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Amanda</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
        <td>Y</td>
      </tr>
    </tbody>
  </table>
</div>

我编辑了您的代码。这是您要找的吗?