首页 文章

带有垂直滚动的html表

提问于
浏览
2

我正在尝试使用固定 Headers 的tbody内的垂直滚动条 . 我尝试了链接中提供的解决方案 .

HTML table with 100% width, with vertical scroll inside tbody

table {
width: 100%;
border-spacing: 0;
}

thead, tbody, tr, th, td { display: block; }

thead tr {
/* fallback */
width: 97%;
/* minus scroll bar width */
width: -webkit-calc(100% - 16px);
width:    -moz-calc(100% - 16px);
width:         calc(100% - 16px);
}

tr:after {  /* clearing float */
content: ' ';
display: block;
visibility: hidden;
clear: both;
}

tbody {
height: 100px;
overflow-y: auto;
overflow-x: hidden;
}

tbody td, thead th {
width: 19%;  /* 19% is less than (100% / 5 cols) = 20% */
float: left;
}

如果滚动条出现,它可以正常工作 . 但是如果行很少并且没有出现滚动条,那么thead就不会与tbody对齐 . 我该如何解决css的问题?

enter image description here

3 回答

  • 0

    一旦您的tbody数据从指定高度移出,您的y轴就会被激活 .

    tbody {
            height: 50px;
            display: inline-block;
            width: 100%;
            overflow-y:scroll;
        }
    
  • 4

    这是因为上面的CSS将 thead tr 宽度的宽度减小到97%或(100% - 滚动条的宽度)以适应缩小的tbody宽度,因为仅在tbody中使用滚动条 . 如果tbody中没有滚动条,则tbody保持完全100%宽,但thead仍在缩小 .

    你希望修复的是CSS,CSS无法识别滚动条没有足够的行显示的事实 . 您将能够使用 JavaScript 修复它 - 只需查看您引用的答案,有一些示例使用 JavaScript 在答案开始时将tbody列的宽度应用于thead .

    EDIT

    或者始终强制垂直滚动条,这样无论行数如何,tbody的宽度都不会改变:

    tbody {
        # ... other attributes
        overflow-y: scroll;
    }
    

    取自:Force Vertical Scrollbar

  • 1

    使用 tbody max-height:100px 而不是 height:100px

    tbody {
        max-height: 100px;
        overflow-y: auto;
        overflow-x: hidden;
    }
    

相关问题