CSS big grid of non-fixed number of squares in one page

I am trying to make a grid of a non-fixed number of squares (5000-6000). Each box should be at least 4x4px tall with a gap of 1px. The grid should use the entire page, so you don’t have to scroll. Every element should be as big as possible so there is less white space. The number of columns or rows should be dynamically chosen. If the page is changing in size the squares will also change and trying to fill the page.

At the moment I have the following code. The problem is that each square is fixed in size. How can I scale each square, so the page is full? In the end, the page should look something like this picture.

var html = "";
for(i=0; i < 5000; i++){
  html += `<div class="box"></div>`;
document.getElementById("grid").innerHTML += html;
.wrapper {
  max-width: 100%;
  max-height: 100%;
  display: grid;
  grid-gap: 1px;
  grid-template-columns: repeat(auto-fill, minmax(4px, 1fr));
  grid-auto-rows: 4px;
  grid-auto-flow: row;
  width: 100%;
  height: 100%;
  float: left;
  background: #4679BD;
.box:before {
  content: "";
  display: block;
  padding-top: 50%;
  <div id="grid" class="wrapper"></div>


My idea is to calculate the area of the screen and divide it into the requested boxes. Then arrange all the boxes with flex.

I also added a calculation that reduces the number of boxes if the last line is not full.

Note that I only added a 1 pixel margin at the bottom and on the right side of each box. If you want a bigger margin, you'll have to take this into account on your calculation.

function showSquares() {
  var html = "";
  var screenWidth = $(window).width();
  var screenHeight = $(window).height();
  var boxesNumber = 5000;
  var marginSize = 1;
  var minSize = 4;
  var minBoxTotalArea = Math.pow((2 * marginSize) + minSize);
  var screenArea = screenWidth * screenHeight;
  var boxSize = "";
  if (screenArea / minBoxTotalArea > boxesNumber) {
    boxesNumber = screenArea / boxTotalArea;
    boxSize = 4;
  } else {
    boxSize = Math.floor(Math.sqrt(screenArea / boxesNumber)) - marginSize;
  /* remove the last line if it's not full */
  var lineLength = Math.floor(screenWidth / (boxSize + marginSize));
  boxesNumber -= boxesNumber % lineLength;
  for (i = 0; i < boxesNumber; i++) {
    html += '<div class="box"></div>';
  document.getElementById("grid").innerHTML = html;
  $(".box").css("width", boxSize + "px");
  $(".box").css("height", boxSize + "px");
$(window).on("resize load", function() {
body {
  padding: 0;
  margin: 0;
.wrapper {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
.box {
  margin-right: 1px;
  margin-bottom: 1px;
  box-sizing: border-box;
  border: 2px solid #454545;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div id="grid" class="wrapper"></div>