简体   繁体   中英

HTML table fitting screen height with squared cells

  var grid = document.getElementById("grid"); var size = 50; for (var y = 0; y < size; y++) { var currentRow = grid.insertRow(0); for (var x = 0; x < size; x++) { var currentCell = currentRow.insertCell(-1); currentCell.style.height = currentCell.style.width = `calc(100vh / ${size})`; currentCell.style.backgroundColor = (x+y)%2 == 0 ? "Blue" : "Red"; } } 
 body { margin: 0; } table#grid { border-collapse: collapse; height: 100%; } 
 <html> <body> <table id="grid" align="center"></table> </body> </html> 

What I need is a table that fits screen height and has squared cells . I tried almost everything , the best result I got using hidden images. The cells are almost squared, not enough for my needs though. Of course I don't want to use any absolute spacing. In fact I would like to do it without images too, just plain CSS/JavaScript. The size of the table will just be known at runtime, but let's assume it's 2 by 2:

<table>
    <tr>
        <td><img src='placeholder.png'></td>
        <td><img src='placeholder.png'></td>
    </tr>
    <tr>
        <td><img src='placeholder.png'></td>
        <td><img src='placeholder.png'></td>
    </tr>
</table>

And in the CSS

table {
    height: 100%;
}

img {
    height: 100%;
    width: auto;
    visibility: hidden
}

Any ideas (that are not too over-sophisticated) are very much appreciated.

You can use CSS calc to calculate height and width, I don't know if it is exactly what you want, but you can try it here:

 .blue { background-color: blue; } .red { background-color: red; } body { margin: 0; } td { height: calc(100vh / 2); width: calc(100vh / 2); } table { border-collapse: collapse; } 
 <table> <tr> <td class="blue"></td> <td class="red"></td> </tr> <tr> <td class="red"></td> <td class="blue"></td> </tr> </table> 

You can also add some javascript code if you need to change your grid size, and calculate the new height and width of each cell.

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