HTML固定标题-将位置th与td在同一级别上对齐

HTML Fixed header - Align position th at the same level as td

本文关键字:一级 对齐 td 标题 th 位置 HTML      更新时间:2024-02-28

我创建了一个具有固定标题和滚动的表。它工作得很好,但表头对齐与表数据不匹配。我的意思是,结果应该是

--------------------
Id Heading2 Heading3
--------------------
 1  value1   value2
 2  value1   value2
 3  value1   value2

但在我的表中,表头与表数据不匹配,这意味着表头没有正确对齐。这是我的小提琴。我试过padding。但它没有起作用。所以,请帮助如何对齐标题以匹配相应的列?JQuery和Javascript解决方案也是可以接受的。

试试这个css:

 thead >tr,th
    {
       border:none;
       padding:5px 20px 5px 10px;
       text-align: center;
       background-color:#0B3B17; 
       font-size:12pt;
    }
    td
    {
      border:none;
      color:#61210B; 
      text-align: center;
      padding: 3px 5px;
    }
    table
    {
     display: block ;
     height: 100px;
     overflow-y: scroll;
     width:400px;
     background-color: #ddd;
   }

试试这个:

html:

<table>
   <thead>
        <tr>
            <th class="id">Id</th>
            <th>Name</th>
            <th>Job</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="id">1</td>
            <td class="name">Raja</td>
            <td class="position">developer</td>
        </tr>
        <tr>
            <td class="id">2</td>
            <td class="name">Rajesh</td>
            <td class="position">associate consultant</td>
        </tr>
        <tr>
            <td class="id">2</td>
            <td class="name">Rajesh</td>
            <td class="position">associate consultant</td>
        </tr>
        <tr>
            <td class="id">2</td>
            <td class="name">Rajesh</td>
            <td class="position">associate consultant</td>
        </tr>
        <tr>
            <td class="id">2</td>
            <td class="name">Rajesh</td>
            <td class="position">associate consultant</td>
        </tr>
    </tbody>
</table>

css:

 thead tr th
{
    color:red;
    text-align:center;
    width:100px;
}
tbody
{
    position: absolute;
    height: 100px;
    overflow: scroll;
    background-color:red;
}
tbody tr td
{
    width:100px;
}
.id
{
    text-align:right;
}
.name, .position
{
    text-align:center;
}