Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive table: move cell to new line if table too small

I'm in a situation where I need to use a table, but I also want it to be responsive.

For some point under max-width: 500px, I would like to convert my third <td> elements to second line with 100% width and others with 50% width each.

I know that with display: block on the <td>'s I can place them beneath each other, something I will do eventually. But I want that step in between.

table {
    height: 400px;
    width: 100%;
}
table tr td:nth-child(1) {
    background-color: red;
}
table tr td:nth-child(2) {
    background-color: green;
}
table tr td:nth-child(3) {
    background-color: blue;
}
@media screen and (max-width: 500px) {
    table tr td:nth-child(3) {
        background-color: pink;
        clear: both;
        display: block;
        width: 100%;
    }
    table tr td:nth-child(1), table tr td:nth-child(2) {
        display: block;
        width: 50%;
    }
}
<table>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table>

(Fiddle version)

I already tried different display variaties like inline-block. Is this at all possible? And preferably without JS?

like image 793
Paul van den Dool Avatar asked Mar 17 '15 17:03

Paul van den Dool


1 Answers

Inline-block works if you deal with the whitespace around the cells so that two 50%-width elements fit:

table {
    ...
    border-spacing: collapse;
}
td {
    padding: 0;
}

Demo

Notice that I've removed some of the unnecessary styles from your third cell.

like image 134
isherwood Avatar answered Sep 23 '22 05:09

isherwood