如何在同一个tr内的新行上获得每个和后续的td对?

时间:2014-07-02 13:14:35

标签: css webkit

我有以下HTML结构(遗憾的是我无法更改):

<table>
    <tbody>
        <tr>
            <th>Name:</th>
            <td>foo</td>
            <th>Address:</th>
            <td>bar</td>
        </tr>
        <tr>
            <th>Name:</th>
            <td>foobaz</td>
            <th>Address:</th>
            <td>barbaz</td>
        </tr>
    </tbody>
</table>

请注意,th / td对的数量可能会有所不同,但在一个表格中它们是稳定的。

我正在尝试使用CSS在每一行上添加一对<th><td>,以便上述HTML呈现为:

Name:    foo
Address: bar

Name:    foobaz
Address: barbaz

我尝试使用以下CSS将<th>转换为float:left

th {
    color:red;
    float:left;
    position:relative;
    display:block;
}

td的类似努力:

td {
    display:block;
    float:left;
    color:green;
    position:relative;
}

但我认为某些über-CSS-table-cell-rule比我尝试应用的规则更强。

我需要应用哪些CSS规则来实现所需的渲染?

我在webkit引擎的上下文中使用它,所以我对WebKit开放 - 只有CSS规则。

您可以找到a JSFiddle here

2 个答案:

答案 0 :(得分:4)

如果你浮动<th>,你可以使用clear:left将它全部分解为separte行:

th {
    color:red;
    float:left;
    clear:left;
    position:relative;
    display:block; 
}
td {
    display:block; 
    float:left;
    color:green;
}
td:last-child {
    padding-bottom:15px;
}

我添加了一些额外的底部填充来创建空行

这是一个working fiddle

答案 1 :(得分:3)

您可以将表更改为不再呈现为表,而是作为常规块元素。通过一些浮动和清除,可以获得类似于您想要的结果。添加伪选择器以设置边距,然后你就可以了。

th:first-child + td行是在IE 8中使用nth-child的方法

table, tr, th, td
{
    display: block;
}

th
{
    color: red;
    clear: left;
    float: left;
}

td
{
    float: left;
    color: green;
}

th:first-child, th:first-child + td
{
    margin-top: 1em;
}

小提琴:http://jsfiddle.net/m2sr7/7/