Search code examples
csswebkit

How can I get each th and following td pair on a new line within the same tr?


I have the following HTML structure (which I can't change unfortunately):

<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>

Do note that the number of th/td pairs can vary, but within one table they are stable.

And I'm trying to use CSS to get on each line a pair of a <th> and a <td> so that the above HTML would render as:

Name:    foo
Address: bar

Name:    foobaz
Address: barbaz

I tried the following CSS to let the <th> to float:left.

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

And similar effort for the td:

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

But I assume some über-CSS-table-cell-rule is stronger than the rules I try to apply.

Which CSS-rule(s) do I need to apply to achieve the desired rendering?

I'm using this in the context of a webkit-engine, so I'm open for WebKit-only CSS-rules.

You can find a JSFiddle here.


Solution

  • You can change the table to no longer render as a table but as a regular block element. With some floating and clearing, it's possible to achieve a result similar to what you want. Add pseudo-selectors to set margins and you're there.

    The th:first-child + td line is a way to use nth-child in IE 8

    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;
    }
    

    Fiddle: http://jsfiddle.net/m2sr7/7/