【问题标题】:Table header and body are not getting aligned properly when table header freezed using CSS使用 CSS 冻结表头时,表头和正文未正确对齐
【发布时间】:2012-10-27 06:23:18
【问题描述】:

当我尝试使用以下 css 修复其头部时,我有一个以下格式的表格,我失去了对齐,表格标题和正文没有正确对齐..我能做些什么来克服这个..

#ex_table
{

table-layout: fixed !important;
}

#ex_table thead tr
{
position: fixed !important;

}

这里是 HTML 部分

<div class="table_div" style="height:400px;width:98%;overflow:scroll">
<table  id="ex_table">
/*thead and tbody populated dynamically via jquery datatables*/
<tfoot id="ex_footer">
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot> 
</table>
</div>

【问题讨论】:

    标签: html css datatables


    【解决方案1】:

    您必须严格设置单元格的宽度:

    th, td { 宽度:30 像素 }

    【讨论】:

    • 这可能是最接近问题的地方,我认为您的问题在于表格布局:已修复,这意味着表格不会根据内容进行调整,这意味着必须明确设置 td 宽度
    【解决方案2】:

    将您的标题行宽度设置为表格宽度:

    #ex_table thead tr
    {
      width:98%;
      position: fixed !important;
    }
    

    【讨论】:

      【解决方案3】:

      答案没那么简单,需要做很多工作。 position: fixed 在使用表格时无法按预期工作,因此您需要另一种方法

      这是我通过网络搜索整理的一个 JSFiddle,http://jsfiddle.net/UWS6N/1/

      在 Stackoverflow 上也发现了这个,这是一个已经回答的问题,它涉及一些 jQuery,我个人喜欢用 CSS 做这样的事情,因为它更快。

      Table header to stay fixed at the top when user scrolls it out of view with jQuery

      另外,请仅为标题行保留&lt;th&gt; 标签,使用&lt;thead&gt; 作为该特定行的容器将有助于代码可读性,将它们放在&lt;tfoot&gt; 中是违反标准的(这有点苛刻表达我知道,但我是一个标准的倡导者,当我看到糟糕的代码时往往会有点前卫,这可能只是我)

      【讨论】:

        【解决方案4】:

        无论用户在页面的哪个位置,固定定位都会将元素保持在视口中的同一位置。因此,如果您在 TR 上使用此属性,它们都会堆叠在视口(浏览器窗口)的左上角。

        【讨论】:

          【解决方案5】:

          我结合了@RomanTheGreat 和@Smiter 证明的解决方案,并编写了一个如下给出的 CSS...尽管对齐方式不是音高完美。这几乎让我到了那里

          #ex_table
              {
              table-layout: fixed !important;
              }
              #ex_table thead tr
              {
               width:500px !important;
               position: fixed !important;
              }
              #ex_table tbody tr
              {
               width:500px!important;
              } 
              #ex_table th, td { width:100px; }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-10-21
            • 1970-01-01
            • 1970-01-01
            • 2014-05-15
            • 2022-08-09
            • 2021-01-12
            • 2017-05-21
            相关资源
            最近更新 更多