使用 HTML 和 CSS 滚动表格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14834198/
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 05:34:18  来源:igfitidea点击:

Table scroll with HTML and CSS

htmlcsshtml-table

提问by Mohamed Naguib

I have a table like that which i fill with a data

我有一个像我填充数据的表格

<table id="products-table"  style="overflow-y:scroll" >
    <thead>
        <tr>
            <th>Product (Parent Product)</th> 
            <th>Associated Sites</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < Model.Count(); i++)
        { 
        <tr>
            <td>
                <a href="Edit"><strong>@Model.ElementAt(i).Name</strong></a><br />
            </td>
            <td>
                <span class="lesser"></span>
            </td>
            <td>@Html.ActionLink("Edit Product", "Edit", "Products")<br />
                @Html.ActionLink("Associate Site", "Associate", "Products")
            </td>
         </tr>
        }
        <tr>
</tbody>
</table>

and CSS like that

和 CSS 那样

    #products-table
{
     width: 200px;
    height: 400px;
    overflow:scroll;
}

but scroll doesn't work, I want to fix the height of the table and if it exceeds, then work with scrollbar

但是滚动不起作用,我想修复表格的高度,如果超过,则使用滚动条

回答by Garry

Table with Fixed Header

带有固定标题的表格

<table cellspacing="0" cellpadding="0" border="0" width="325">
  <tr>
    <td>
       <table cellspacing="0" cellpadding="1" border="1" width="300" >
         <tr style="color:white;background-color:grey">
            <th>Header 1</th>
            <th>Header 2</th>
         </tr>
       </table>
    </td>
  </tr>
  <tr>
    <td>
       <div style="width:320px; height:80px; overflow:auto;">
         <table cellspacing="0" cellpadding="1" border="1" width="300" >
           <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
           <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
              <tr>
             <td>new item</td>
             <td>new item</td>
           </tr>
         </table>  
       </div>
    </td>
  </tr>
</table>

Result

结果

Demo Image

演示图片

This is working in all browser

这适用于所有浏览器

Demo jsfiddle http://jsfiddle.net/nyCKE/6302/

演示 jsfiddle http://jsfiddle.net/nyCKE/6302/

回答by Jan Turoň

Late answer, another idea, but very short.

迟到的答案,另一个想法,但很短。

  1. put the contents of header cells into div
  2. fix the header contents, see CSS
  1. 将标题单元格的内容放入 div
  2. 修复标题内容,请参阅 CSS
table  { margin-top:  20px; display: inline-block; overflow: auto; }
th div { margin-top: -20px; position: absolute; }

Note that it is possible to display table as inline-block due to anonymous table objects:

请注意,由于匿名表对象,可以将表显示为内联块:

"missing" [in HTML table tree structure] elements must be assumed in order for the table model to work. Any table element will automatically generate necessary anonymous table objects around itself.

必须假定“缺少”[在 HTML 表格树结构中] 元素才能使表格模型正常工作。任何表格元素都会在其周围自动生成必要的匿名表格对象。

/* scrolltable rules */
table  { margin-top:  20px; display: inline-block; overflow: auto; }
th div { margin-top: -20px; position: absolute; }

/* design */
table { border-collapse: collapse; }
tr:nth-child(even) { background: #EEE; }
<table style="height: 150px">
  <tr> <th><div>first</div> <th><div>second</div>
  <tr> <td>foo <td>bar
  <tr> <td>foo foo foo foo foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar bar bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
  <tr> <td>foo <td>bar
</table>

回答by patrickdamery

For those wondering how to implement Garry's solution with more than one header this is it:

对于那些想知道如何使用多个标题来实现 Garry 的解决方案的人来说,它是这样的:

#wrapper {
  width: 235px;
}

table {
  border: 1px solid black;
  width: 100%;
}

th,
td {
  width: 100px;
  border: 1px solid black;
}

thead>tr {
  position: relative;
  display: block;
}

tbody {
  display: block;
  height: 80px;
  overflow: auto;
}
<div id="wrapper">
  <table>
    <thead>
      <tr>
        <th>column1</th>
        <th>column2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>row1</td>
        <td>row1</td>
      </tr>
      <tr>
        <td>row2</td>
        <td>row2</td>
      </tr>
      <tr>
        <td>row3</td>
        <td>row3</td>
      </tr>
      <tr>
        <td>row4</td>
        <td>row4</td>
      </tr>
    </tbody>
  </table>
</div>

回答by Gawran

Works only in Chrome but it can be adapted to other modern browsers. Table falls back to common table with scroll bar in other brws. Uses CSS3 FLEX property.

仅适用于 Chrome,但它可以适用于其他现代浏览器。表格回退到其他 brws 中带有滚动条的普通表格。使用 CSS3 FLEX 属性。

http://jsfiddle.net/4SUP8/1/

http://jsfiddle.net/4SUP8/1/

<table border="1px" class="flexy">
    <caption>Lista Sumnjivih vozila:</caption>
    <thead>
        <tr>
            <td>Opis Sumnje</td>
        <td>Registarski<br>broj vozila</td>
        <td>Datum<br>Vreme</td>
        <td>Brzina<br>(km/h)</td>
        <td>Lokacija</td>
        <td>Status</td>
        <td>Akcija</td>
        </tr>
    </thead>
    <tbody>

        <tr>
        <td>Osumnji?en tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>

        <tr>
        <td>Osumnji?en tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>

        <tr>
        <td>Osumnji?en tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>


        <tr>
        <td>Osumnji?en tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>

    </tbody>
</table>

Style (CSS 3):

样式(CSS 3):

caption {
    display: block;
    line-height: 3em;
    width: 100%;
    -webkit-align-items: stretch;
    border: 1px solid #eee;
}

       .flexy {
            display: block;
            width: 90%;
            border: 1px solid #eee;
            max-height: 320px;
            overflow: auto;
        }

        .flexy thead {
            display: -webkit-flex;
            -webkit-flex-flow: row;
        }

        .flexy thead tr {
            padding-right: 15px;
            display: -webkit-flex;
            width: 100%;
            -webkit-align-items: stretch;
        }

        .flexy tbody {
            display: -webkit-flex;
            height: 100px;
            overflow: auto;
            -webkit-flex-flow: row wrap;
        }
        .flexy tbody tr{
            display: -webkit-flex;
            width: 100%;
        }

        .flexy tr td {
            width: 15%;
        }

回答by Mohamad Hamouday

This work for me

这对我有用

Demo: jsfiddle

演示:jsfiddle

$(function() 
{
    Fixed_Header();
});


function Fixed_Header()
{
    $('.User_Table thead').css({'position': 'absolute'});
    $('.User_Table tbody tr:eq("2") td').each(function(index,e){
        $('.User_Table thead tr th:eq("'+index+'")').css({'width' : $(this).outerWidth() +"px" });
    });
    var Header_Height = $('.User_Table thead').outerHeight();
    $('.User_Table thead').css({'margin-top' : "-"+Header_Height+"px"});
    $('.User_Table').css({'margin-top' : Header_Height+"px"});
}

回答by Thinesh Thinesh

<div style="overflow:auto">
    <table id="table2"></table>
</div>

Try this code for overflow table it will work only on div tag

试试这个溢出表的代码,它只适用于 div 标签

回答by Penny Liu

Adds a fading gradient to an overflowing HTML table element to better indicate there is more content to be scrolled.

向溢出的 HTML 表格元素添加渐变渐变,以更好地指示有更多内容要滚动。

  • Table with fixed header
  • Overflow scroll gradient
  • Custom scrollbar
  • 表头固定
  • 溢出滚动渐变
  • 自定义滚动条

See the live example below:

请参阅下面的实时示例:

$("#scrolltable").html("<table id='cell'><tbody></tbody></table>");
$("#cell").append("<thead><tr><th><div>First col</div></th><th><div>Second col</div></th></tr></thead>");

for (var i = 0; i < 40; i++) {
  $("#scrolltable > table > tbody").append("<tr><td>" + "foo" + "</td><td>" + "bar" + "</td></tr>");
}
/* Table with fixed header */

table,
thead {
  width: 100%;
  text-align: left;
}

#scrolltable {
  margin-top: 50px;
  height: 120px;
  overflow: auto;
  width: 200px;
}

#scrolltable table {
  border-collapse: collapse;
}

#scrolltable tr:nth-child(even) {
  background: #EEE;
}

#scrolltable th div {
  position: absolute;
  margin-top: -30px;
}


/* Custom scrollbar */

::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
}


/* Overflow scroll gradient */

.overflow-scroll-gradient {
  position: relative;
}

.overflow-scroll-gradient::after {
  content: '';
  position: absolute;
  bottom: 0;
  width: 240px;
  height: 25px;
  background: linear-gradient( rgba(255, 255, 255, 0.001), white);
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overflow-scroll-gradient">
  <div id="scrolltable">
  </div>
</div>

回答by Sebastian Rothbucher

For whatever it's worth now: here is yet another solution:

无论现在值多少钱:这是另一个解决方案:

  • create two divs within a display: inline-block
  • in the first div, put a table with only the header (header table tabhead)
  • in the 2nd div, put a table with header and data (data table / full table tabfull)
  • use JavaScript, use setTimeout(() => {/*...*/})to execute code after render / after filling the table with results from fetch
  • measure the width of each th in the data table (using clientWidth)
  • apply the same width to the counterpart in the header table
  • set visibility of the header of the data table to hidden and set the margin top to -1 * height of data table thead pixels
  • 在一个内创建两个 div display: inline-block
  • 在第一个 div 中,放置一个只有标题的表格(标题表tabhead
  • 在第二个 div 中,放置一个带有标题和数据的表(数据表/完整表tabfull
  • 使用 JavaScript,用于setTimeout(() => {/*...*/})在渲染后/用结果填充表格后执行代码fetch
  • 测量数据表中每个 th 的宽度(使用clientWidth
  • 对标题表中的对应项应用相同的宽度
  • 将数据表标题的可见性设置为隐藏,并将边距顶部设置为 -1 * 数据表顶部像素的高度

With a few tweaks, this is the method to use (for brevity / simplicity, I used d3js, the same operations can be done using plain DOM):

通过一些调整,这是要使用的方法(为了简洁/简单,我使用了 d3js,可以使用普通 DOM 完成相同的操作):

setTimeout(() => { // pass one cycle
  d3.select('#tabfull')
    .style('margin-top', (-1 * d3.select('#tabscroll').select('thead').node().getBoundingClientRect().height) + 'px')
    .select('thead')
      .style('visibility', 'hidden');
  let widths=[]; // really rely on COMPUTED values
  d3.select('#tabfull').select('thead').selectAll('th')
    .each((n, i, nd) => widths.push(nd[i].clientWidth));
  d3.select('#tabhead').select('thead').selectAll('th')
    .each((n, i, nd) => d3.select(nd[i])
          .style('padding-right', 0)
          .style('padding-left', 0)
          .style('width', widths[i]+'px'));
})

Waiting on render cycle has the advantage of using the browser layout engine thoughout the process - for any type of header; it's not bound to special condition or cell content lengths being somehow similar. It also adjusts correctly for visible scrollbars (like on Windows)

等待渲染周期的优点是在整个过程中使用浏览器布局引擎 - 对于任何类型的标题;它不受特殊条件或单元格内容长度的限制。它还可以正确调整可见滚动条(如在 Windows 上)

I've put up a codepen with a full example here: https://codepen.io/sebredhh/pen/QmJvKy

我在这里放了一个带有完整示例的代码笔:https://codepen.io/sebredhh/pen/QmJvKy

回答by Ferdys Duran

  .outer {
    overflow-y: auto;
    height: 300px;
  }

  .outer {
    width: 100%;
    -layout: fixed;
  }

  .outer th {
    text-align: left;
    top: 0;
    position: sticky;
    background-color: white;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>MYCRUD</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>

<div class="container-fluid col-md-11">
  <div class="row">

    <div class="col-lg-12">

   
        <div class="card-body">
          <div class="outer">

            <table class="table table-hover bg-light">
              <thead>
                <tr>
                  <th scope="col">ID</th>
                  <th scope="col">Marca</th>
                  <th scope="col">Editar</th>
                  <th scope="col">Eliminar</th>
                </tr>
              </thead>
              <tbody>

                
                  <tr>
                    <td>4</td>
                    <td>Toyota</td>
                    <td> <a class="btn btn-success" href="#">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td> <a class="btn btn-danger" href="#">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>

                                  <tr>
                    <td>3</td>
                    <td>Honda </td>
                    <td> <a class="btn btn-success" href="#">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td> <a class="btn btn-danger" href="#">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>

                                  <tr>
                    <td>5</td>
                    <td>Myo</td>
                    <td> <a class="btn btn-success" href="#">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td> <a class="btn btn-danger" href="#">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>

                                  <tr>
                    <td>6</td>
                    <td>Acer</td>
                    <td> <a class="btn btn-success" href="#">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td> <a class="btn btn-danger" href="#">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>

                                  <tr>
                    <td>7</td>
                    <td>HP</td>
                    <td> <a class="btn btn-success" href="#">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td> <a class="btn btn-danger" href="#">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>

                                  <tr>
                    <td>8</td>
                    <td>DELL</td>
                    <td> <a class="btn btn-success" href="#">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td> <a class="btn btn-danger" href="#">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>

                                  <tr>
                    <td>9</td>
                    <td>LOGITECH</td>
                    <td> <a class="btn btn-success" href="#">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td> <a class="btn btn-danger" href="#">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>

                              </tbody>
            </table>
          </div>

        </div>

     




    </div>

  </div>

</div>

</body>
</html>