html table with vertical scroll inside tbody

I am trying for a vertical scroll bar inside tbody with a fixed header. I tried solution provided in the link.

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;
}

It works fine if scroll bar appears.But if the rows are few and the scroll bar doesn't appear, then thead is not aligned with tbody. How can I fix the issue with css?


一旦你的tbody数据从指定的高度移出,你的y轴被激活。

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

That's because the CSS above reduces the width of the thead tr 's width to 97% or (100% - the width of the scrollbar) to accomodate for the reduced width of the tbody because of the scrollbar in tbody only. If there is no scrollbar in tbody then the tbody remains fully 100% wide but the thead is still being narrowed.

You wish to fix is with the CSS, well the CSS cannot recognize the fact that there are not enough rows to for the scrollbar to show. You will be able to fix it using JavaScript though - just look in the answer you have cited, there are examples of using JavaScript to apply the width of the tbody columns to thead just at the beginning of the answer.

EDIT

Or force vertical scrollbar at all times, such that the width of the tbody doesn't change regardless of the row count:

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

taken from: Force Vertical Scrollbar


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

tbody {
    max-height: 100px;
    overflow-y: auto;
    overflow-x: hidden;
}
链接地址: http://www.djcxy.com/p/88298.html

上一篇: 100%宽度的HTML表格,tbody内没有td wdth的垂直滚动

下一篇: html表格与tbody内的垂直滚动