HTML表格标题作为标题行的一部分

时间:2014-12-18 14:12:20

标签: html css

我想创建一个表标题行,其左侧包含标题,右侧包含“Sample header”。对于可访问性和语义正确,标题应该在<caption>标记中,但“Sample header”不是标题的一部分,因此它可能不应该在<caption>内。标题不能在行内,因为它必须是<table>之后的第一个元素。

这是HTML结构:

<table>
    <caption>Caption</caption>
    <thead>
        <tr class="sample">
            <th colspan="2">Sample header</th>
        </tr>
        <tr>
            <th>Column1</th>
            <th>Column2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Data1</td>
            <td>Data2</td>
        </tr>
    </tbody>
</table>

标题最终作为表格上方的单独行,而我希望它与“Sample header”位于同一行。

以下是我正在尝试实现的示例:http://jsfiddle.net/vueLL5ce/5/。它将'caption`的位置设置为relative,并手动将其移动到我想要的位置。这种方法的两个主要问题是重新定位标题仍然使其原始空间位于表格之上,我正在使用不同浏览器之间的像素,因此它不一定正确排列。

有没有一种很好的方法来实现这一目标?我是否坚持在<caption>中包含标题信息(并且样式看起来像表格行)或创建常规表格行而不使用<caption>

2 个答案:

答案 0 :(得分:1)

将背景颜色从div移动到表格,它应该从顶部删除颜色。见附件小提琴here

table {
border: solid 1px Black;
width: 100%;
background-color: #FFFFDD;

}

我会删除标题,使用列标题并将两个项目与自己的类分开,然后在css中对齐它们。更新了示例here这样就完全没有间距问题了。

答案 1 :(得分:0)

我想我找到了一个跨浏览器的解决方案。关键是设置line-height: 0(普通0在IE6中不起作用,但我不需要支持它)。 Firefox也不会让我直接重新定位标题,所以我不得不添加另一个span。我仍然不喜欢直接处理像素,所以任何有关这方面的建议都会很棒。

小提琴:http://jsfiddle.net/vueLL5ce/8/

HTML:

<div>
    <table>
        <caption><span>Caption</span></caption>
        <thead>
            <tr class="captionRow">
                <th colspan="2">Sample header</th>
            </tr>
            <tr>
                <th>Column1</th>
                <th>Column2</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Data1</td>
                <td>Data2</td>
            </tr>
        </tbody>
    </table>
</div>

CSS:

div {
    background-color: #FFFFDD;
}

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

table caption {
    line-height: 0;
    text-align: left;
}

table caption span {
    position: relative;
    left: 4px;
    top: 14px;
}

table th {
    background-color: #CCC;
}

.captionRow th {
    text-align: right;
}