Search code examples
htmlcsshtml-tablecss-positionsticky

How to use position sticky for horizontal scrollbar?


I need to scroll table according to X axis. My code looks like this. I tried also position fixeb but for some reason it scroll work only on Y axis. What I am doing wrong?

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>


Solution

  • I think you just need the sticky on the first column:

    .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>

    The solution's from a post on CSS-Tricks.