const container = document.querySelector('div') const tiles = document.querySelectorAll('tile') function recalcTilewidth(){ const container_width = container.offsetWidth const container_height = container.offsetHeight // only if it fills the entire container const tile_width = container_width / tiles.length const tile_height = container_height let bestCount = 1; let bestDiff = Infinity; // Try from 1 to some reasonable max (e.g. 100 tiles) for (let count = 1; count <= 100; count++) { const tileWidth = container_width / count; const aspectRatio = tileWidth / container_height; const diff = Math.abs(aspectRatio - 1); if (diff < bestDiff) { bestDiff = diff; bestCount = count; } // Stop early if perfect square if (diff < 0.01) break; } return bestCount; } const count = recalcTilewidth(); console.log(count)
div { display: flex; width: 600px; height: 300px; background: blue; } tile { display: block; width: 100%; height: 100%; border: 1px solid white; }