JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container"></div>
CSS
.container {
box-shadow: inset 0px 0px 0px 1px black;
position: absolute;
display: block;
height: 81vh;
width: 46vw;
}
.block {
box-shadow: inset 0px 0px 0px 1px black;
position: absolute;
display: block;
height: 10vh;
width: 10vh;
}
JavaScript
$(document).ready(function () {
resizeSquares();
});
$(window).on('resize', function () {
resizeSquares();
});
function resizeSquares() {
$('.container').html('');
var length = 12;
var height = document.getElementsByClassName('container')[0].offsetHeight;
var width = document.getElementsByClassName('container')[0].offsetWidth;
var area = width * height;
var maxBlockArea = parseInt(area / length);
var maxBlockLength = parseInt(Math.sqrt(maxBlockArea));
var columns = Math.ceil(width / (maxBlockLength*0.8));
var rows = Math.ceil(height / (maxBlockLength));
var blockWidth = Math.floor(width / columns);
var blockHeight = Math.floor(height / rows);
//if you can fit more cards in the bottom column, remove a column
var bottomRowBlocks = columns - parseInt(((length / columns) % 1) * columns);
//bottomRowBlocks = bottomRowBlocks === columns ? 0 : bottomRowBlocks;
//when you remove a column you have to add to bottom column as one block from each row except the bottom one
var freeRows = rows - Math.ceil(length / columns);
//- 1 because you won't have one column when one collapses
var freeSpaces = (freeRows * (columns - 1)) + bottomRowBlocks - 1;
if (freeSpaces > parseInt(length / columns) - 1) {
columns = columns - 1;
if (freeRows > 0) {
rows = rows + freeRows;
}
}
blockWidth = Math.floor(width / columns);
blockHeight = Math.floor(height / rows);
if (blockHeight > (blockWidth / (17 / 19))) {
blockHeight = blockWidth / (17 / 19);
} else {
blockWidth = blockHeight * (17 / 19);
}
var leftMargin = (width - ((parseInt(columns)) * blockWidth)) / (columns - 1);
if (leftMargin < 1) {
leftMargin = 0;
blockWidth = Math.floor(width / columns);
blockHeight = blockWidth / (17 / 19);
} else {
if(rows > parseInt(length/columns) + 1) {
blockHeight = Math.floor(height /...