css 如何使具有固定标题和左列的表适应窗口大小?

tf7tbtn2  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(136)

我有一个CSS文件来锁定html表的头和列,但是如果我试图使外框适应窗口大小,锁定功能就会丢失。我该如何克服这个问题?
这是我的CSS的一部分:

body, html, table {
...
}

table {
  position: relative;
  background-color: #ffd699; /* First column, same as first header cell */
  overflow: hidden;
  border-collapse: collapse;
}

/*thead*/
thead {
  position: relative;
  display: block; /* Separates the header from the body allowing it to be positioned*/
  width: 1600px; /* Total scrollable header width, same as tbody width */
  overflow: visible;
}

thead th {
...
}

thead th:nth-child(1) {/*The first cell in the header*/
  position: relative;
  display: block; /* Separates the first cell in the header from the header*/
...
}

thead tr th:nth-child(1) {  /* The first header cell in each tr*/
  position: relative;
  display: block; /* Separates the first column from the thead*/
...
}

/*tbody*/
tbody {
  position: relative;
  display: block; /* Separates the tbody from the header*/
  width: 1600px; /* Total scrollable tbody width, same as header width */
  height: 800px;  /* Total scrollable tbody height */
  overflow: scroll;
  border: 1px solid white;
} 

tbody td { /* Table cells */
...
}

tbody tr td:nth-child(1) {  /*The first cell in each tr*/
  position: relative;
  display: block; /* Separates the first column from the tbody*/
...
  border-top: 0px solid white;
}

零件被排除在外了。我插入了width:window。innerWidth和height:window.innerHeight,但没有成功。

fcg9iug3

fcg9iug31#

基于您共享的URL MTL_Istaby.html
这段jQuery代码可以帮助您,无论是window.innerWidth还是100%
window.innerWidth

$(document).ready(function() {
   $('table').css('width', window.innerWidth - 25 + "px");
   $('table').css('display', 'block')
   
   $( window ).on( "resize", function() {
      $('table').css('width', window.innerWidth - 25 + "px");
   });

})

百分百

$(document).ready(function() {
   $('table').css('width', "100%");
   $('table').css('display', 'block')
})

你也可以尝试css 100%宽度的表和display: block将自动占用浏览器的宽度

table {
  position: relative;
  background-color: #ffd699; /* First column, same as first header cell */
  overflow: hidden;
  border-collapse: collapse;
  display: block;
  width: 100%
}

相关问题