100% 宽度的 HTML 表格,在 tbody 内垂直滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17067294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:21:40  来源:igfitidea点击:

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

htmlcssvertical-scrolling

提问by Marko S

How can I set for <table>100% width and put only inside <tbody>vertical scroll for some height?

如何设置<table>100% 宽度并仅将<tbody>垂直滚动放在某个高度?

vertical scroll inside tbody

tbody 内的垂直滚动

table {
    width: 100%;
    display:block;
}
thead {
    display: inline-block;
    width: 100%;
    height: 20px;
}
tbody {
    height: 200px;
    display: inline-block;
    width: 100%;
    overflow: auto;
}
  
<table>
  <thead>
    <tr>
     <th>Head 1</th>
     <th>Head 2</th>
     <th>Head 3</th>
     <th>Head 4</th>
     <th>Head 5</th>
    </tr>
  </thead>
  <tbody>
    <tr>
     <td>Content 1</td>
     <td>Content 2</td>
     <td>Content 3</td>
     <td>Content 4</td>
     <td>Content 5</td>
    </tr>
  </tbody>
</table>

I want to avoid adding some additional div, all I want is simple table like this and when I trying to change display, table-layout, positionand much more things in CSS table not working good with 100% width only with fixed width in px.

我希望避免增加一些额外的div,我要的是简单的表像这样,当我试图改变显示table-layoutposition和CSS表更事情不是100%的宽度仅与PX固定宽度的工作好。

回答by Hashem Qolami

In order to make <tbody>element scrollable, we need to change the way it's displayed on the page i.e. using display: block;to display that as a block level element.

为了使<tbody>元素可滚动,我们需要更改它在页面上的显示方式,即使用display: block;将其显示为块级元素。

Since we change the displayproperty of tbody, we should change that property for theadelement as well to prevent from breaking the table layout.

由于我们更改了 的display属性tbody,因此我们也应该更改thead元素的该属性以防止破坏表格布局。

So we have:

所以我们有:

thead, tbody { display: block; }

tbody {
    height: 100px;       /* Just for the demo          */
    overflow-y: auto;    /* Trigger vertical scroll    */
    overflow-x: hidden;  /* Hide the horizontal scroll */
}

Web browsers display the theadand tbodyelements as row-group(table-header-groupand table-row-group) by default.

默认情况下,Web 浏览器将theadtbody元素显示为行组table-header-grouptable-row-group)。

Once we change that, the inside trelements doesn't fill the entire space of their container.

一旦我们改变了它,内部tr元素就不会填满它们容器的整个空间。

In order to fix that, we have to calculate the width of tbodycolumns and apply the corresponding value to the theadcolumns via JavaScript.

为了解决这个问题,我们必须计算tbody列的宽度并thead通过 JavaScript将相应的值应用于列。

Auto Width Columns

自动宽度列

Here is the jQuery version of above logic:

这是上述逻辑的 jQuery 版本:

// Change the selector if needed
var $table = $('table'),
    $bodyCells = $table.find('tbody tr:first').children(),
    colWidth;

// Get the tbody columns width array
colWidth = $bodyCells.map(function() {
    return $(this).width();
}).get();

// Set the width of thead columns
$table.find('thead tr').children().each(function(i, v) {
    $(v).width(colWidth[i]);
});    

And here is the output (on Windows 7 Chrome 32):

这是输出(在 Windows 7 Chrome 32 上)

vertical scroll inside tbody

tbody 内的垂直滚动

WORKING DEMO.

工作演示

Full Width Table, Relative Width Columns

全宽表,相对宽度列

As the Original Poster needed, we could expand the tableto 100% of widthof its container, and then using a relative (Percentage) widthfor each columns of the table.

根据原始海报的需要,我们可以将其扩展tablewidth其容器的100% ,然后对表的每一列使用相对值 ( Percentage) width

table {
    width: 100%; /* Optional */
}

tbody td, thead th {
    width: 20%;  /* Optional */
}

Since the table has a (sort of) fluid layout, we should adjust the width of theadcolumns when the container resizes.

由于表格具有(某种)流体布局,我们应该thead在容器调整大小时调整列的宽度。

Hence we should set the columns' widths once the window is resized:

因此,我们应该在调整窗口大小后设置列的宽度:

// Adjust the width of thead cells when *window* resizes
$(window).resize(function() {
    /* Same as before */ 
}).resize(); // Trigger the resize handler once the script runs

The output would be:

输出将是:

Fluid Table with vertical scroll inside tbody

Fluid Table with vertical scroll inside tbody

WORKING DEMO.

工作演示



Browser Support and Alternatives

浏览器支持和替代品

I've tested the two above methods on Windows 7 via the new versions of major Web Browsers (including IE10+) and it worked.

我已经通过新版本的主要 Web 浏览器(包括 IE10+)在 Windows 7 上测试了上述两种方法并且它有效。

However, it doesn'tworkproperlyon IE9and below.

但是,它工作正常上IE9及以下。

That's because in a table layout, all elements should follow the same structural properties.

那是因为表格布局中,所有元素都应该遵循相同的结构属性。

By using display: block;for the <thead>and <tbody>elements, we've broken the table structure.

通过使用display: block;for<thead><tbody>元素,我们打破了表结构。

Redesign layout via JavaScript

通过 JavaScript 重新设计布局

One approach is to redesign the (entire) table layout. Using JavaScript to create a new layout on the fly and handle and/or adjust the widths/heights of the cells dynamically.

一种方法是重新设计(整个)表格布局。使用 JavaScript 动态创建新布局并动态处理和/或调整单元格的宽度/高度。

For instance, take a look at the following examples:

例如,请看以下示例:

Nesting tables

嵌套表

This approach uses two nested tables with a containing div. The first tablehas only one cell which has a div, and the second table is placed inside that divelement.

这种方法使用两个带有包含 div 的嵌套表。第一个table只有一个单元格有一个div,第二个表格放置在该div元素内。

Check the Vertical scrolling tablesat CSS Play.

检查垂直滚动表CSS播放

This works on most of web browsers. We can also do the above logic dynamically via JavaScript.

这适用于大多数网络浏览器。我们还可以通过 JavaScript 动态地执行上述逻辑。

Table with fixed header on scroll

滚动时带有固定标题的表格

Since the purpose of adding vertical scroll bar to the <tbody>is displaying the table headerat the top of each row, we could positionthe theadelement to stay fixedat the top of the screen instead.

由于添加垂直滚动条的目的<tbody>是显示表在每一行的顶部,我们可以定位thead元件停留fixed在屏幕代替的顶部。

Here is a Working Demoof this approach performed by Julien.
It has a promising web browser support.

这是Julien执行的这种方法的工作演示。 它有一个很有前途的网络浏览器支持。

And herea pure CSSimplementation by Willem Van Bockstal.

而且在这里一个纯CSS通过实施威廉·Bockstal



The Pure CSS Solution

纯 CSS 解决方案

Here is the old answer. Of course I've added a new method and refined the CSS declarations.

这是旧答案。当然,我已经添加了一个新方法并改进了 CSS 声明。

Table with Fixed Width

固定宽度的桌子

In this case, the tableshould have a fixed width(including the sum of columns' widths and the width of vertical scroll-bar).

在这种情况下,table应该有一个固定的width(包括列的宽度和垂直滚动条的宽度)

Each columnshould have a specific widthand the last columnof theadelement needs a greater widthwhich equals to the others' width+ the widthof vertical scroll-bar.

应该有一个特定的宽度,元素的最后一列thead需要更大的宽度,等于其他列的宽度+垂直滚动条的宽度

Therefore, the CSS would be:

因此,CSS 将是:

table {
    width: 716px; /* 140px * 5 column + 16px scrollbar width */
    border-spacing: 0;
}

tbody, thead tr { display: block; }

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

tbody td, thead th {
    width: 140px;
}

thead th:last-child {
    width: 156px; /* 140px + 16px scrollbar width */
}

Here is the output:

这是输出:

Table with Fixed Width

Table with Fixed Width

WORKING DEMO.

工作演示

Table with 100% Width

100% 宽度的桌子

In this approach, the tablehas a width of 100%and for each thand td, the value of widthproperty should be less than 100% / number of cols.

在这种方法中,每个andtable的宽度100%thand tdwidth属性的值应该小于100% / number of cols

Also, we need to reduce the widthof theadas value of the widthof vertical scroll-bar.

此外,我们需要降低宽度thead作为的值宽度垂直滚动条的。

In order to do that, we need to use CSS3 calc()function, as follows:

为此,我们需要使用 CSS3calc()函数,如下所示:

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

Here is the Online Demo.

这是在线演示

Note:This approach will failif the content of each column breaks the line, i.e. the content of each cell should be short enough.

注意:如果每列的内容断行,这种方法将失败,即每个单元格的内容应该足够短



In the following, there are two simple example of pure CSS solutionwhich I created at the time I answered this question.

下面是我在回答这个问题时创建的纯 CSS 解决方案的两个简单示例。

Here is the jsFiddle Demov2.

这是jsFiddle Demov2

Old version: jsFiddle Demov1

旧版本:jsFiddle Demov1

回答by tsayen

In following solution, table occupies 100% of the parent container, no absolute sizes required. It's pure CSS, flex layout is used.

在下面的解决方案中,表占据了父容器的 100%,不需要绝对大小。它是纯 CSS,使用 flex 布局。

Here is how it looks: enter image description here

这是它的外观: enter image description here

Possible disadvantages:

可能的缺点:

  • vertical scrollbar is always visible, regardless of whether it's required;
  • table layout is fixed - columns do not resize according to the content width (you still can set whatever column width you want explicitly);
  • there is one absolute size - the width of the scrollbar, which is about 0.9em for the browsers I was able to check.
  • 垂直滚动条始终可见,无论是否需要;
  • 表格布局是固定的 - 列不会根据内容宽度调整大小(您仍然可以明确设置您想要的任何列宽);
  • 有一个绝对大小 - 滚动条的宽度,对于我能够检查的浏览器来说大约是 0.9em。

HTML (shortened):

HTML(缩短):

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>head1</th>
                <th>head2</th>
                <th>head3</th>
                <th>head4</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>content1</td>
                <td>content2</td>
                <td>content3</td>
                <td>content4</td>
            </tr>
            <tr>
                <td>content1</td>
                <td>content2</td>
                <td>content3</td>
                <td>content4</td>
            </tr>
            ...
        </tbody>
    </table>
</div>

CSS, with some decorations omitted for clarity:

CSS,为了清楚起见省略了一些装饰:

.table-container {
    height: 10em;
}
table {
    display: flex;
    flex-flow: column;
    height: 100%;
    width: 100%;
}
table thead {
    /* head takes the height it requires, 
    and it's not scaled when table is resized */
    flex: 0 0 auto;
    width: calc(100% - 0.9em);
}
table tbody {
    /* body takes all the remaining available space */
    flex: 1 1 auto;
    display: block;
    overflow-y: scroll;
}
table tbody tr {
    width: 100%;
}
table thead, table tbody tr {
    display: table;
    table-layout: fixed;
}

full code on jsfiddle

jsfiddle 上的完整代码

Same code in LESS so you can mix it in:

LESS 中的相同代码,因此您可以将其混入:

.table-scrollable() {
  @scrollbar-width: 0.9em;
  display: flex;
  flex-flow: column;

  thead,
  tbody tr {
    display: table;
    table-layout: fixed;
  }

  thead {
    flex: 0 0 auto;
    width: ~"calc(100% - @{scrollbar-width})";
  }

  tbody {
    display: block;
    flex: 1 1 auto;
    overflow-y: scroll;

    tr {
      width: 100%;
    }
  }
}

回答by Gauss

In modern browsers, you can simply use css:

在现代浏览器中,您可以简单地使用 css:

th {
  position: sticky;
  top: 0;
  z-index: 2;
}

回答by gavroche

I'm using display:blockfor theadand tbody. Because of that the width of the theadcolumns is different from the width of the tbodycolumns.

我正在使用display:blockfortheadtbody。因此,thead列的宽度与tbody列的宽度不同。

table {
    margin:0 auto; 
    border-collapse:collapse;
}
thead {
    background:#CCCCCC;
    display:block
}
tbody {
    height:10em;overflow-y:scroll;
    display:block
}

To fix this I use small jQuerycode but it can be done in JavaScriptonly.

为了解决这个问题,我使用了小jQuery代码,但它只能在里面完成JavaScript

var colNumber=3 //number of table columns    

for (var i=0; i<colNumber; i++) {
  var thWidth=$("#myTable").find("th:eq("+i+")").width();
  var tdWidth=$("#myTable").find("td:eq("+i+")").width();      
  if (thWidth<tdWidth)                    
      $("#myTable").find("th:eq("+i+")").width(tdWidth);
  else
      $("#myTable").find("td:eq("+i+")").width(thWidth);           
}  

Here is my working demo: http://jsfiddle.net/gavroche/N7LEF/

这是我的工作演示:http: //jsfiddle.net/gavroche/N7LEF/

Does not work in IE 8

不适用于 IE 8

var colNumber=3 //number of table columns


for (var i=0; i<colNumber; i++)
  {
      var thWidth=$("#myTable").find("th:eq("+i+")").width();
      var tdWidth=$("#myTable").find("td:eq("+i+")").width();      
      if (thWidth<tdWidth)                    
          $("#myTable").find("th:eq("+i+")").width(tdWidth);
      else
          $("#myTable").find("td:eq("+i+")").width(thWidth);           
  }  
 table {margin:0 auto; border-collapse:separate;}
 thead {background:#CCCCCC;display:block}
 tbody {height:10em;overflow-y:scroll;display:block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" border="1">
    <thead>
        <tr>
            <th>A really Very Long Header Text</th>
            <th>Normal Header</th>
            <th>Short</th>            
        </tr>    
    </thead>
    <tbody>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
        <tr>
            <td>
                Text shorter than header
            </td>
            <td>
                Text is longer than header
            </td>
            <td>
                Exact
            </td>
        </tr>
    </tbody>
</table>

回答by Roko C. Buljan

CSS-only

仅 CSS

for Chrome, Firefox, Edge(and other evergreenbrowsers)

适用于Chrome、Firefox、Edge(和其他常绿浏览器)

Simply position: sticky; top: 0;your thelements:

只是position: sticky; top: 0;你的th元素:

/* Fix table head */
.tableFixHead    { overflow-y: auto; height: 100px; }
.tableFixHead th { position: sticky; top: 0; }

/* Just common table stuff. */
table  { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th     { background:#eee; }
<div class="tableFixHead">
  <table>
    <thead>
      <tr><th>TH 1</th><th>TH 2</th></tr>
    </thead>
    <tbody>
      <tr><td>A1</td><td>A2</td></tr>
      <tr><td>B1</td><td>B2</td></tr>
      <tr><td>C1</td><td>C2</td></tr>
      <tr><td>D1</td><td>D2</td></tr>
      <tr><td>E1</td><td>E2</td></tr>
    </tbody>
  </table>
</div>

PS: if you need bordersfor TH elements th {box-shadow: 1px 1px 0 #000; border-top: 0;}will help (since the default borders are not painted correctly on scroll).

PS:如果您需要TH 元素的边框th {box-shadow: 1px 1px 0 #000; border-top: 0;}会有所帮助(因为默认边框在滚动时未正确绘制)。

For a variant of the above that uses just a bit of JS in order to accommodate for IE11see this answer https://stackoverflow.com/a/47923622/383904

对于仅使用一点 JS 以适应IE11的上述变体,请参阅此答案https://stackoverflow.com/a/47923622/383904

回答by Sushil Kumar

Create two tables one after other, put second table in a div of fixed height and set the overflow property to auto. Also keep all the td's inside thead in second table empty.

一个接一个地创建两个表,将第二个表放在一个固定高度的div中,并将overflow属性设置为auto。还要将第二个表中的所有 td 内的 td 保持为空。

<div>
    <table>
        <thead>
            <tr>
                <th>Head 1</th>
                <th>Head 2</th>
                <th>Head 3</th>
                <th>Head 4</th>
                <th>Head 5</th>
            </tr>
        </thead>
    </table>
</div>

<div style="max-height:500px;overflow:auto;">
    <table>
        <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <tr>
            <td>Content 1</td>
            <td>Content 2</td>
            <td>Content 3</td>
            <td>Content 4</td>
            <td>Content 5</td>
        </tr>
        </tbody>
    </table>    
</div>

回答by Mikael Lepist?

I got it finally right with pure CSS by following these instructions:

按照以下说明,我最终使用纯 CSS 正确完成了:

http://tjvantoll.com/2012/11/10/creating-cross-browser-scrollable-tbody/

http://tjvantoll.com/2012/11/10/creating-cross-browser-scrollable-tbody/

The first step is to set the <tbody>to display: block so an overflow and height can be applied. From there the rows in the <thead>need to be set to position: relative and display: block so that they'll sit on top of the now scrollable <tbody>.

第一步是设置<tbody>to display: 块,以便可以应用溢出和高度。从那里<thead>需要将需要设置为 position:relative 和 display:block 的行,以便它们将位于现在可滚动的顶部<tbody>

tbody, thead { display: block; overflow-y: auto; }

tbody, thead { display: block; overflow-y: auto; }

Because the <thead>is relatively positioned each table cell needs an explicit width

因为<thead>相对定位,每个表格单元格都需要一个明确的宽度

td:nth-child(1), th:nth-child(1) { width: 100px; }
td:nth-child(2), th:nth-child(2) { width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }

But unfortunately that is not enough. When a scrollbar is present browsers allocate space for it, therefore, the <tbody>ends up having less space available than the <thead>. Notice the slight misalignment this creates...

但不幸的是,这还不够。当滚动条存在时,浏览器会为其分配空间,因此,<tbody>最终可用空间少于<thead>. 请注意这造成的轻微错位...

The only workaround I could come up with was to set a min-width on all columns except the last one.

我能想出的唯一解决方法是在除最后一列之外的所有列上设置最小宽度。

td:nth-child(1), th:nth-child(1) { min-width: 100px; }
td:nth-child(2), th:nth-child(2) { min-width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }

Whole codepen example below:

整个codepen示例如下:

CSS:

CSS:

.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed_headers th {
  text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
}
.fixed_headers thead {
  background-color: #333333;
  color: #fdfdfd;
}
.fixed_headers thead tr {
  display: block;
  position: relative;
}
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
  background-color: #dddddd;
}
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
}
.old_ie_wrapper tbody {
  height: auto;
}

Html:

网址:

<!-- IE < 10 does not like giving a tbody a height.  The workaround here applies the scrolling to a wrapped <div>. -->
<!--[if lte IE 9]>
<div class="old_ie_wrapper">
<!--<![endif]-->

<table class="fixed_headers">
  <thead>
    <tr>
      <th>Name</th>
      <th>Color</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Pear</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Grape</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
    </tr>
    <tr>
      <td>Orange</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Banana</td>
      <td>Yellow</td>
      <td>These are yellow.</td>
    </tr>
    <tr>
      <td>Kiwi</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Plum</td>
      <td>Purple</td>
      <td>These are Purple</td>
    </tr>
    <tr>
      <td>Watermelon</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Tomato</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cherry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cantelope</td>
      <td>Orange</td>
      <td>These are orange inside.</td>
    </tr>
    <tr>
      <td>Honeydew</td>
      <td>Green</td>
      <td>These are green inside.</td>
    </tr>
    <tr>
      <td>Papaya</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Raspberry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Blueberry</td>
      <td>Blue</td>
      <td>These are blue.</td>
    </tr>
    <tr>
      <td>Mango</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Passion Fruit</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
  </tbody>
</table>

<!--[if lte IE 9]>
</div>
<!--<![endif]-->

EDIT: Alternative solution for table width 100% (above actually is for fixed width and didn't answer the question):

编辑:表格宽度 100% 的替代解决方案(上面实际上是固定宽度,没有回答问题):

HTML:

HTML:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Color</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Pear</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Grape</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
    </tr>
    <tr>
      <td>Orange</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Banana</td>
      <td>Yellow</td>
      <td>These are yellow.</td>
    </tr>
    <tr>
      <td>Kiwi</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
  </tbody>
</table>

CSS:

CSS:

table {
  width: 100%;
  text-align: left;
  min-width: 610px;
}
tr {
  height: 30px;
  padding-top: 10px
}
tbody { 
  height: 150px; 
  overflow-y: auto;
  overflow-x: hidden;
}
th,td,tr,thead,tbody { display: block; }
td,th { float: left; }
td:nth-child(1),
th:nth-child(1) {
  width: 20%;
}
td:nth-child(2),
th:nth-child(2) {
  width: 20%;
  float: left;
}
td:nth-child(3),
th:nth-child(3) {
  width: 59%;
  float: left;
}
/* some colors */
thead {
  background-color: #333333;
  color: #fdfdfd;
}
table tbody tr:nth-child(even) {
  background-color: #dddddd;
}

Demo: http://codepen.io/anon/pen/bNJeLO

演示:http: //codepen.io/anon/pen/bNJeLO

回答by Emmanuel

Css workaround for forcing columns to display correctly with a 'block' tbody

强制使用“块”tbody 正确显示列的 Css 解决方法

This solution still requires the thwidths to be calculated and set by jQuery

此解决方案仍然需要th由 jQuery 计算和设置宽度

table.scroll tbody,
table.scroll thead { display: block; }

table.scroll tbody {
    overflow-y: auto;
    overflow-x: hidden;
    max-height: 300px;
}

table.scroll tr {
    display: flex;
}

table.scroll tr > td {
    flex-grow: 1;
    flex-basis: 0;
}

And the Jquery / Javascript

和 Jquery / Javascript

var $table = $('#the_table_element'),
    $bodyCells = $table.find('tbody tr:first').children(),
    colWidth;

$table.addClass('scroll');

// Adjust the width of thead cells when window resizes
$(window).resize(function () {

    // Get the tbody columns width array
    colWidth = $bodyCells.map(function () {
        return $(this).width();
    }).get();

    // Set the width of thead columns
    $table.find('thead tr').children().each(function (i, v) {
        $(v).width(colWidth[i]);
    });

}).resize(); // Trigger resize handler

回答by Nandha

try below approach, very simple easy to implement

尝试以下方法,非常简单易于实现

Below is the jsfiddle link

下面是jsfiddle链接

http://jsfiddle.net/v2t2k8ke/2/

http://jsfiddle.net/v2t2k8ke/2/

HTML:

HTML:

<table border='1' id='tbl_cnt'>
<thead><tr></tr></thead><tbody></tbody>

CSS:

CSS:

 #tbl_cnt{
 border-collapse: collapse; width: 100%;word-break:break-all;
 }
 #tbl_cnt thead, #tbl_cnt tbody{
 display: block;
 }
 #tbl_cnt thead tr{
 background-color: #8C8787; text-align: center;width:100%;display:block;
 }
 #tbl_cnt tbody {
 height: 100px;overflow-y: auto;overflow-x: hidden;
 }

Jquery:

查询:

 var data = [
    {
    "status":"moving","vehno":"tr544","loc":"bng","dri":"ttt"
    }, {
    "status":"stop","vehno":"tr54","loc":"che", "dri":"ttt"
    },{    "status":"idle","vehno":"yy5499999999999994","loc":"bng","dri":"ttt"
    },{
    "status":"moving","vehno":"tr544","loc":"bng", "dri":"ttt"
    }, {
    "status":"stop","vehno":"tr54","loc":"che","dri":"ttt"
    },{
    "status":"idle","vehno":"yy544","loc":"bng","dri":"ttt"
    }
    ];
   var sth = '';
   $.each(data[0], function (key, value) {
     sth += '<td>' + key + '</td>';
   });
   var stb = '';        
   $.each(data, function (key, value) {
       stb += '<tr>';
       $.each(value, function (key, value) {
       stb += '<td>' + value + '</td>';
       });
       stb += '</tr>';
    });
      $('#tbl_cnt thead tr').append(sth);
      $('#tbl_cnt tbody').append(stb);
      setTimeout(function () {
      var col_cnt=0 
      $.each(data[0], function (key, value) {col_cnt++;});    
      $('#tbl_cnt thead tr').css('width', ($("#tbl_cnt tbody") [0].scrollWidth)+ 'px');
      $('#tbl_cnt thead tr td,#tbl_cnt tbody tr td').css('width',  ($('#tbl_cnt thead tr ').width()/Number(col_cnt)) + 'px');}, 100)

回答by codegeek

Adding a fixed width to td,thafter making tbody& theaddisplay block works perfectly and also we can use slimscrollplugin to make the scroll bar beautiful.

td添加固定宽度使tbodythead显示块完美运行后,我们还可以使用slimscroll插件使滚动条变得漂亮。

enter image description here

enter image description here

<!DOCTYPE html>
<html>

<head>
    <title> Scrollable table </title>
    <style>
        body {
            font-family: sans-serif;
            font-size: 0.9em;
        }
        table {
            border-collapse: collapse;
            border-bottom: 1px solid #ddd;
        }
        thead {
            background-color: #333;
            color: #fff;
        }
        thead,tbody {
            display: block;
        }
        th,td {
            padding: 8px 10px;
            border: 1px solid #ddd;
            width: 117px;
            box-sizing: border-box;
        }
        tbody {
            height: 160px;
            overflow-y: scroll
        }
    </style>
</head>

<body>

    <table class="example-table">
        <thead>
            <tr>
                <th> Header 1 </th>
                <th> Header 2 </th>
                <th> Header 3 </th>
                <th> Header 4 </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td> Row 1- Col 1 </td>
                <td> Row 1- Col 2 </td>
                <td> Row 1- Col 3 </td>
                <td> Row 1- Col 4 </td>
            </tr>
            <tr>
                <td> Row 2- Col 1 </td>
                <td> Row 2- Col 2 </td>
                <td> Row 2- Col 3 </td>
                <td> Row 2- Col 4 </td>
            </tr>
            <tr>
                <td> Row 3- Col 1 </td>
                <td> Row 3- Col 2 </td>
                <td> Row 3- Col 3 </td>
                <td> Row 3- Col 4 </td>
            </tr>
            <tr>
                <td> Row 4- Col 1 </td>
                <td> Row 4- Col 2 </td>
                <td> Row 4- Col 3 </td>
                <td> Row 4- Col 4 </td>
            </tr>
            <tr>
                <td> Row 5- Col 1 </td>
                <td> Row 5- Col 2 </td>
                <td> Row 5- Col 3 </td>
                <td> Row 5- Col 4 </td>
            </tr>
            <tr>
                <td> Row 6- Col 1 </td>
                <td> Row 6- Col 2 </td>
                <td> Row 6- Col 3 </td>
                <td> Row 6- Col 4 </td>
            </tr>
            <tr>
                <td> Row 7- Col 1 </td>
                <td> Row 7- Col 2 </td>
                <td> Row 7- Col 3 </td>
                <td> Row 7- Col 4 </td>
            </tr>
            <tr>
                <td> Row 8- Col 1 </td>
                <td> Row 8- Col 2 </td>
                <td> Row 8- Col 3 </td>
                <td> Row 8- Col 4 </td>
            </tr>
            <tr>
                <td> Row 9- Col 1 </td>
                <td> Row 9- Col 2 </td>
                <td> Row 9- Col 3 </td>
                <td> Row 9- Col 4 </td>
            </tr>
            <tr>
                <td> Row 10- Col 1 </td>
                <td> Row 10- Col 2 </td>
                <td> Row 10- Col 3 </td>
                <td> Row 10- Col 4 </td>
            </tr>
            <tr>
                <td> Row 11- Col 1 </td>
                <td> Row 11- Col 2 </td>
                <td> Row 11- Col 3 </td>
                <td> Row 11- Col 4 </td>
            </tr>
            <tr>
                <td> Row 12- Col 1 </td>
                <td> Row 12- Col 2 </td>
                <td> Row 12- Col 3 </td>
                <td> Row 12- Col 4 </td>
            </tr>
            <tr>
                <td> Row 13- Col 1 </td>
                <td> Row 13- Col 2 </td>
                <td> Row 13- Col 3 </td>
                <td> Row 13- Col 4 </td>
            </tr>
            <tr>
                <td> Row 14- Col 1 </td>
                <td> Row 14- Col 2 </td>
                <td> Row 14- Col 3 </td>
                <td> Row 14- Col 4 </td>
            </tr>
            <tr>
                <td> Row 15- Col 1 </td>
                <td> Row 15- Col 2 </td>
                <td> Row 15- Col 3 </td>
                <td> Row 15- Col 4 </td>
            </tr>
            <tr>
                <td> Row 16- Col 1 </td>
                <td> Row 16- Col 2 </td>
                <td> Row 16- Col 3 </td>
                <td> Row 16- Col 4 </td>
            </tr>
        </tbody>
    </table>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-slimScroll/1.3.8/jquery.slimscroll.min.js"></script>
    <script>
        $('.example-table tbody').slimscroll({
            height: '160px',
            alwaysVisible: true,
            color: '#333'
        })
    </script>
</body>

</html>