简体   繁体   中英

Amount of table columns based on width of display

I am designing a website and on desktop I have a 2 column table, however on mobile the table does not look as good. Is it possible to determine the amount of table columns based on the screen width?

Desktop:

Cell 1     Cell 2
Cell 3     Cell 4

Mobile:

Cell 1
Cell 2
Cell 3
Cell 4

It can be done by applying display:flex to your tr and adjusting the td size in a media query

 table{width:100%;} tr { display: flex; flex-wrap: wrap; width:100%; } td { width: 50%; border:1px solid blue; box-sizing:border-box; } @media screen and (max-width:400px) { td{width:100%;} } 
 <table> <tr> <td>col 1</td> <td>col 2</td> </tr> <tr> <td>col 3</td> <td>col 4</td> </tr> </table> 

You can find a functional example here

I've answered a similar question here: Forcing table cell onto new row

Quite simply, what you're trying to do here is to make a table not behave as a table, which is interesting implementation. That being said, you could do something like this: https://jsfiddle.net/jz6mypvw/1/

Using @media queries, you can force your table to split into rows as the window gets smaller. The example below will be 2x2 when the screen width is < 800px , and finally one single column when the size is < 500px .

@media only screen and (max-width: 800px) {
    table tr td {
        display: block;
        width: 50%;
        box-sizing: border-box;
        float: left;
    }
}

@media only screen and (max-width: 500px) {
    table tr td {
        width: 100%;
    }
}
<table>
    <tr>
        <td class="col-1">One</td>
        <td class="col-2">Two</td>
        <td class="col-3">Three</td>
        <td class="col-4">Four</td>
    </tr>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM