首页 > 解决方案 > 如何将位置粘性用于水平滚动条?

问题描述

我需要根据 X 轴滚动表格。我的代码看起来像这样。我也尝试过定位 fixeb,但由于某种原因它只能在 Y 轴上滚动。我做错了什么?

HTML

table {
    margin-top: 20px;
    width: 100%;
}
table,
th,
td {
    border: 1px solid black;
    border-collapse: collapse;
}
th,
td {
    padding: 10px;
    text-align: left;
}
th {
    font-weight: 700;
    position: sticky;
}
<table>
    <tr>
        <th>Some header</th>
        <td>1</td>
        <td>2</td>
        ...
        <td>20</td>
    </tr>
    <tr>
        <th>Some header</th>
        <td>1</td>
        <td>2</td>
        ...
        <td>20</td>
    </tr>
    <table></table>
</table>

标签: htmlcsshtml-tablecss-positionsticky

解决方案


我认为你只需要第一列的粘性:

.wrapper {
  max-width: 400px;
  overflow-x: scroll;
}

table {
  position: relative;
  border: 1px solid #ddd;
  border-collapse: collapse;
}

td, th {
  white-space: nowrap;
  border: 1px solid #ddd;
  padding: 20px;
  text-align: center;
}

td:first-of-type {
  background-color: #eee;
  position: sticky;
  left: -1px;
  text-align: left;
}
<div class="wrapper">
<table>
  <tbody>
    <tr>
        <td>Some header</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
    </tr>
    <tr>
        <td>Some header</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
    </tr>
  </tbody>
</table>
</div>

解决方案来自CSS-Tricks上的帖子。


推荐阅读