如何在可滚动的 div 中制作固定的标题表?

新手上路,请多包涵

我想修复表的标题。表格存在于可滚动的 div 中。下面是我的代码。

 <div id="table-wrapper">
    <div id="table-scroll">
        <table bgcolor="white" border="0" cellpadding="0" cellspacing="0" id="header-fixed" width="100%" overflow="scroll" class="scrollTable">
            <thead>
                <tr>
                    <th>Order ID</th>
                    <th>Order Date</th>
                    <th>Status</th>
                    <th>Vol Number</th>
                    <th>Bonus Paid</th>
                    <th>Reason for no Bonus</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><%=snd.getOrderId()%></td>
                    <td><%=snd.getDateCaptured()%></td>
                    <td><%=snd.getOrderStatus()%></td>
                    <td>Data Not Available</td>
                    <td>Data Not Available</td>
                    <td>Data Not Available</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

下面是我用于上述 div 的 CSS:

 #table-wrapper {
    position:relative;
}

#table-scroll {
    height:250px;
    overflow:auto;
    margin-top:20px;
}

#table-wrapper table {
    width:100%;
}

#table-wrapper table * {
    background:white;
    color:black;
}

#table-wrapper table thead th .text {
    position:absolute;
    top:-20px;
    z-index:2;
    height:20px;
    width:35%;
    border:1px solid red;
}

原文由 Rohan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 322
2 个回答

做这样的事情怎么样?我是从零开始做的…

我所做的是使用 2 个表,一个用于标题,它始终是静态的,另一个表呈现单元格,我使用 div 具有固定高度的元素包装,并启用滚动,我正在使用 overflow-y: auto;

Also make sure you use table-layout: fixed; with fixed width td elements so that your table doesn’t break when a string without white space is used , 所以为了打破我正在使用的字符串 word-wrap: break-word;

演示

.wrap {
    width: 352px;
}

.wrap table {
    width: 300px;
    table-layout: fixed;
}

table tr td {
    padding: 5px;
    border: 1px solid #eee;
    width: 100px;
    word-wrap: break-word;
}

table.head tr td {
    background: #eee;
}

.inner_table {
    height: 100px;
    overflow-y: auto;
}

<div class="wrap">
    <table class="head">
        <tr>
            <td>Head 1</td>
            <td>Head 1</td>
            <td>Head 1</td>
        </tr>
    </table>
    <div class="inner_table">
        <table>
        <tr>
            <td>Body 1</td>
            <td>Body 1</td>
            <td>Body 1</td>
        </tr>
        <!-- Some more tr's -->
    </table>
    </div>
</div>

原文由 Mr. Alien 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 --- 上使用 position: sticky th 就可以了。

注意:如果您在 theadtr position: sticky ,它将不起作用。

https://jsfiddle.net/hrg3tmxj/

原文由 Tenzin Nyima 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题