今天接到一個任務要用html+css實現表格固定首行首列,水平垂直可以滾動,不可以用javascript
要實現這個功能,表格無法實現,需要通過布局來實現

父容器div內包裹着4個table(1,2,3,4)
在垂直方向,1、2列表頭固定,3、4垂直滾動
在水平方向,1、3行表頭固定,2、4水平滾動
要實現這種效果,可以通過position:sticky;這種定位方式相當與fixed+relative,將1固定死在左上角,設置2垂直固定在頂部,水平可滾動,設置3水平固定在左邊,水平可滾動,4相對定位就好啦
具體實現代碼如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Table</title> <style type="text/css"> *{ margin:0px; padding:0px; } .contain { border: 1px solid #cdd; width: 500px; height: 300px; overflow: scroll; position: relative; float: left; top: 100px; left: 50px; } th, td, tr { border: 1px solid #cdd; height: 30px; width: 100px; text-align: center; } .tb1 { background: gray; position: fixed; z-index: 10001; width: 100px; } .tb2 { background: gray; position: sticky; top: 0px; margin-left: 100px; width: 500px; z-index: 1000; } .tb3 { background: gray; left: 0px; height: 100%; float: left; position: sticky; z-index: 1000; width: 100px; } .tb4 { left: 100px; width: 500px; position: absolute; } </style> </head> <body> <div class="contain"> <table class="tb1" cellspacing="0"> <thead> <th>姓名 </table> <table class="tb2" cellspacing="0"> <thead> <th>Java <th>Python <th>Golang <th>Rust <th>Ruby </table> <table class="tb3" cellspacing="0"> <tbody> <tr> <th>phermis <tr> <th>phermis <tr> <th>phermis <tr> <th>phermis <tr> <th>phermis <tr> <th>phermis <tr> <th>phermis <tr> <th>phermis <tr> <th>phermis </table> <table class="tb4" cellspacing="0"> <tbody> <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 <tr> <td>100 <td>100 <td>100 <td>100 <td>100 </table> </div> </body> </html>
花了一下午總算是按着自己的思路實現了,有需要的朋友可以看下
瀏覽器兼容性不是很好,最新火狐支持,別的未測試
