位置固定的html表

时间:2017-03-08 07:31:15

标签: html css

我使用固定位置来冻结表格中的第一列。如何使它成为与其他列相同的第一列布局(宽度和高度),看起来与其他列没有区别但具有冻结状态。

<div>
 <table>
<tr>
  <th class='td1'>h1</th>
  <th>h2</th>
  <th>h3</th>
</tr>
<tr>
  <td class='td1'>D1</td>
  <td>D2</td>
  <td>D3</td>
</tr>
<tr>
  <td class='td1'>D1</td>
  <td>D2</td>
  <td>D3</td>
</tr>
</table>
</div>

的CSS:

table {
  border-collapse: collapse;
  border: 1px solid black;
  width: 300px;
  height: 300px;
}

tr,
td,
th {
  border: 1px solid black;
  text-align: center;
}

.td1 {
  position: fixed;
  margin-top: 10px;
  margin-left: 10px;
}

div {
  width: 200px;
  height: 400px;
  overflow: auto;
}

JSfiddle demo

2 个答案:

答案 0 :(得分:1)

你的意思是这样吗?

CSS:

table {
  border-collapse: collapse;
  border: 1px solid black;
  width: 300px;
  height: 300px;
}

tr,
td,
th {
  border: 1px solid black;
  text-align: center;
}

.td1 {
position: fixed;
width: 143px;
height: 96px;
margin-left: 5px;
}

div {
  width: 200px;
  height: 400px;
  overflow: auto;
}

HTML:

<div>
 <table>
<tr>
  <th class='td1'>h1</th>
  <th>h2</th>
  <th>h3</th>
</tr>
<tr>
  <td class='td1'>D1</td>
  <td>D2</td>
  <td>D3</td>
</tr>
<tr>
  <td class='td1'>D1</td>
  <td>D2</td>
  <td>D3</td>
</tr>
</table>
</div>

答案 1 :(得分:1)

尝试下面的内容 -

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

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

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

.headcol {
  position: absolute;
  width: 5em;
  left: 0;
  top: auto;
  border-top-width: 1px;
  margin-top: -1px;
}

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

.long {
  background: yellow;
}
<div>
  <table>
    <tr>
      <th class="headcol">h1</th>
      <td class="long">h2</td>
      <td class="long">h3</td>
    </tr>
    <tr>
      <th class="headcol">D1</th>
      <td class="long">D2</td>
      <td class="long">D3</td>
    </tr>
    <tr>
      <th class="headcol">D1</th>
      <td class="long">D2</td>
      <td class="long">D3</td>
    </tr>
  </table>
</div>