如何在表的元素之间正确定位HTML元素(分隔线)

时间:2015-03-17 15:51:12

标签: html css html-table

是否可以在表头和表行之间放置一个HTML元素?

类似我在this plunker中的代码:

<table style="width:100%">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>       
    <th>Header 3</th>
  </tr>
<div style="background-color: #848484; width: 100%; height:1px; margin:0px; padding: 0px;"></div>
  <tr>
    <td>Value 1</td>
    <td>Value 2</td>        
    <td>Value 3</td>
  </tr>
</table>

我目前实现这一目标的方法是在表格之后放置分隔线div并使用相对位置将它放在表格元素之间。但是如果表格标题或正文的高度发生变化,我的位置相对线可能不再出现在标题和正文之间。

插入此分隔线以使其始终位于表格标题和正文之间的最佳方法是什么?

非常感谢你的时间。如果您需要更多信息或我不清楚,请告诉我。

3 个答案:

答案 0 :(得分:2)

您不需要额外的标记就可以在表格中添加一行。只需使用CSS:

&#13;
&#13;
th {
    border-bottom: 2px solid #848484;
}
table {
    border-collapse: collapse; /* remove space between cells */
}
&#13;
<table style="width:100%">
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
        <th>Header 3</th>
    </tr>
    <tr>
        <td>Value 1</td>
        <td>Value 2</td>
        <td>Value 3</td>
    </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

我认为更好的方法是使用THEAD和TBODY然后写一些与你的DIV相同的css

HTML

<thead>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
        <th>Header 3</th>
    </tr>
</thead>

CSS

thead {border-bottom:1px solid #848484;}

答案 2 :(得分:0)

使用border-bottom添加分隔符,并使用:last-child选择器删除最后一行的分隔符。

jsFiddle

HTML

<table style="width:100%">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>       
    <th>Header 3</th>
  </tr>
  <tr>
    <td>Value 1</td>
    <td>Value 2</td>        
    <td>Value 3</td>
  </tr>
  <tr>
    <td>Value 1</td>
    <td>Value 2</td>        
    <td>Value 3</td>
  </tr>
</table>

CSS

tr {
    display: block;
    border-bottom: 11px solid grey;
}

tr:last-child {
    border: none;
}