具有水平滚动的表格标题的位置粘性

Nit*_*n K 6 html css html-table css-position

我有一个 HTML 表格,可以水平滚动但不能垂直滚动

我想在向下滚动时将表格的标题固定到顶部,但是当我position:sticky在元素和overflow-x:scroll父元素上使用时,它不会粘住。

这是问题的示例小提琴https://jsfiddle.net/a53exv28/8/

小智 -2

也许您无法将表格标题设置为水平固定,但您可以这样做

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}


td, th {
    padding: 5px 20px;
    width: 100px;
}

th:first-child {
    position: fixed;
    left: 5px
}
Run Code Online (Sandbox Code Playgroud)
<div class="table-wrapper">
    <table id="consumption-data" class="data">
        <thead class="header">
            <tr>
                <th>Month</th>
                <th>Item 1</th>
                <th>Item 2</th>
                <th>Item 3</th>
                <th>Item 4</th>
            </tr>
        </thead>
        <tbody class="results">
            <tr>
                <th>Jan</th>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
            </tr>
            <tr>
                <th>Feb</th>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
            </tr>
            <tr>
                <th>Mar</th>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
            </tr>
            <tr>
                <th>Apr</th>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>  
            </tr>
            <tr>    
                <th>May</th>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
            </tr>
            <tr>
                <th>Jun</th>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
                <td>3163</td>
            </tr>

            <tr>
                <th>...</th>
                <td>...</td>
                <td>...</td>
                <td>...</td>
                <td>...</td>
            </tr>
        </tbody>
    </table>
</div>
Run Code Online (Sandbox Code Playgroud)