微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 顶部有固定标题的表格

我正在尝试在顶部为我们数据库中的数据创建一个带有固定标头的表.当我添加’position:fixed;’时在标题的css中它将它保持在顶部但它强制整个标题到第一列.如何让表头位于顶部并与列正确对齐?如果可能的话,我更喜欢css / html解决方案.

编辑:我已经尝试了很多我在SO和谷歌上找到的jQuery解决方案.有些工作,有些则没有.当我将其与我在页面上运行的其他脚本结合使用时,那些自行工作的人往往会破坏…

<style>
  .dg_hdr_row{
  position: fixed;
  top:0;
  height: 25px;
  }

  .dg_col1{ width:60%; border: 1px solid #000; padding: 5px;}
  .dg_col2{ width:15%; border: 1px solid #000; padding: 5px;}
  .dg_col3{ width:10%; border: 1px solid #000; padding: 5px;}
  .dg_col4{ width:15%; border: 1px solid #000; padding: 5px;}

</style>

<table width="100%">

 <thead width="100%" >
  <tr width="100%" class="dg_hdr_row" >
   <th width="60%">Column 1</th>
   <th width="15%">Column 2</th>
   <th width="10%">Column 3</th>
   <th width="15%">Column 4</th>
  </tr>
 </thead>

    <tbody>
        <tr class="dg_row">
            <td class="dg_col1"></td>
            <td class="dg_col2"></td>
            <td class="dg_col3"></td>
            <td class="dg_col4"></td>
        </tr>
        <tr class="dg_row">
            <td class="dg_col1"></td>
            <td class="dg_col2"></td>
            <td class="dg_col3"></td>
            <td class="dg_col4"></td>
        </tr>       
    </tbody>
</table>

解决方法

因此,固定定位存在一些微妙的问题,这使得这一点特别困难.

固定元素与浏览器视点相关

声明position:fixed时,任何其他位置规则(如left或top)都会将标题相对于视口本身 – 屏幕的左上角.您也不能使用任何技巧使其相对于其父级,因为只要页面滚动它就会在同一个位置.这可能不会影响您的网页,但仍需要考虑.

固定元素在移动浏览器中无法正常工作

我不知道你的具体用例,但这是值得深思的.

固定定位从正常流动中移除元素

据我所知,这就是造成这个问题的原因.声明position:fixed时,元素实际上会突破页面元素的正常布局和位置,现在可以在自己的唯一块中工作.

CSS2 spec(这也适用于固定定位):

In the absolute positioning model,a Box is explicitly offset with respect to its containing block. It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned Box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However,the contents of an absolutely positioned element do not flow around any other Boxes. They may obscure the contents of another Box (or be obscured themselves),depending on the stack levels of the overlapping Boxes.

这很好,因为你希望标题浮动在表格之上,但也很糟糕,因为在大多数浏览器中,它与表格的其余部分分开布局.

可能的修复

>如果页面上唯一的东西是您的表格,您应该能够将标题设置为使用宽度:100%并应用与表格其余部分相同的单元格宽度.但是,可能很难使大小调整得恰到好处,尤其是在调整窗口大小时.
>使用一些简单的JavaScript来显示标题.我知道你想用HTML和CSS保持这个(我通常也这样做),但是JavaScript非常合适,因为浮动标题不应该是使用网站的重要部分.它应该适用于支持它的浏览器,但那些不支持它的应该仍然可以使用该表. css-Tricks有一个非常好的技巧
(http://css-tricks.com/persistent-headers/),但您可以通过在您最喜欢的搜索引擎上查找“粘性表格标题”来找到其他人.

原文地址:https://www.jb51.cc/html/231486.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐