Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a complex table by using CSS?

Tags:

css

Recently i ran into a complex table implementation, for example:

tr1: | td1 | td2 | td3 |
tr2: |  th  |   td   |
tr3: |  th  |   td   |
...

As this example shows, i want td1 and td3 are width fixed, td and td2 are width auto to expand when screen-radio/browser-width changed. I'm wondering if there is a way to do this by using CSS?

Just to be clear, i already used colspan and width value for my purpose, but how can i make td1 smaller than th by using colspan and width value? colspan doesn't work, neither width value

like image 349
Edward Avatar asked Apr 13 '10 06:04

Edward


3 Answers

It's a simple matter of setting the colspans correctly.

Table Header Row: Each Cell gets a colspan of 2 (3 Cells * 2 colspan = 6 colspan-cells).
Table Body Rows: Each Cell gets a colspan of 3 (2 Cells * 3 colspan = 6 colspan-cells).

UPDATE

There seems to be an inconsistency which involves Columns having both colspan and width set. The Browsers seem to ignore the width value and even max-width (min-width works).

Example:

<table border="1" style="width: 50%;">
    <tr>
        <td style="width: 100px;">td1</td>
        <td colspan="2">td2</td>
        <td style="width: 100px;">td3</td>
    </tr>
    <tr>
        <th colspan="2" style="min-width: 120px; max-width: 120px; width: 120px;">th1</th>
        <td colspan="2">td2</td>
    </tr>
    <tr>
        <th colspan="2" style="min-width: 120px; max-width: 120px; width: 120px;">th1</th>
        <td colspan="2">td2</td>
    </tr>
</table>

This produces roughly the desired output but the th column th1 expands to match the same size of the following td (td2). Both always occupy 50% of the table unless the table is smaller than 240px, then th1 stays at 120px.

This seems inconsistent to me and i have no workaround, best is if you check if you can display the table differently (i.e. same number of columns in all rows including the header (which would make more sense anyways imho)).

like image 67
Morfildur Avatar answered Oct 14 '22 16:10

Morfildur


From that limited example, it looks to me like you need two tables.

One for the top row (explicitly set the width of td1, td3, and the entire table. Let td2 auto expand.

And one for the rest of the table... format it as you please, just set the table width to the same as the top row so it looks like one table. You'll probably have to set 0 margins/padding.

That, or you could make it one table and do some colspan hackery.

like image 3
mpen Avatar answered Oct 14 '22 16:10

mpen


Try these colspans:

tr1: | td1(1) | td2(2) | td3(1) |
tr2: |  td1(2)   |   td2(2)     |
tr3: |  td1(2)   |   td2(2)     |
...
like image 3
pdr Avatar answered Oct 14 '22 18:10

pdr