Search code examples
htmlcsshtml-tablealignmenttext-align

How to line up a table's th cells to be in the middle (on the border) of the td cells below it


grid

I'm trying to create this table layout. Basically the orange 18 you see in the grid means 18% usage between 11am and 12pm on Tuesday. So that's why the hours along the top are best on the edges of the table cell, not in the middle of the cell. That way it's showing the data representing usage over a one hour time range.

I have basically applied a basic hack and right aligned the hours along the top so they kinda look like they're inbetween the cells. This isn't perfect as you can see.

What I want to do is actually have the hours along the top centered nicely between the data cells. I think I could do it with a fixed size column widths, but the table needs to stretch to 100% of the page width and the column widths a percentage. Then it's scalable down to a smaller browser.

Is there a way to do this in HTML and CSS?


Solution

  • To have the first row truly centered between the bottom cells with a single table you can use colspan + widths in percentages without using positioning. That way it will be fluid, it will work with any font, and it won't get screwed when you use 2 digit numbers.

    HTML:

    <table border="0" cellpadding="0" cellspacing="0">
        <tbody>
            <tr>
                <td>&nbsp;</td>
    
                <th colspan="2">1</th>
    
                <th colspan="2">1</th>
    
                <th colspan="2">1</th>
    
                <th colspan="2">1</th>
    
                <th colspan="2">1</th>
    
                <td>&nbsp;</td>
            </tr>
    
            <tr>
                <td colspan="2">0</td>
    
                <td colspan="2">0</td>
    
                <td colspan="2">0</td>
    
                <td colspan="2">0</td>
    
                <td colspan="2">0</td>
    
                <td colspan="2">0</td>
            </tr>
        </tbody>
    </table>
    

    CSS:

    table {
        text-align: center;
        width: 70%;    
        }
    
    table td {
        width:8.33%; // 100% divided by (double the number of bottom cells)
    }
    
    table th {
        width:16.66%; // 200% divided by (double the number of bottom cells)
    }
    
    table td[colspan="2"] {
        background:yellow;
    }
    
    table td,
    table th {
        outline:1px solid tan;
    }
    

    Demo: http://jsfiddle.net/G7KZe/