JSFiddle - React, Tailwind, and code Playground
CSS
body {
background-color: white;
margin: 0;
text-align: center;
overflow: hidden;
}
.grid {
display: inline-block;
background-color: blue;
}
.cellDiv:nth-child(odd) {
background-color: red;
float:left;
}
.cellDiv:nth-child(even) {
background-color: green;
float:left;
}
JavaScript
console.log('width: ' + window.innerWidth, 'height: ' + window.innerHeight)
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var size = 10;
function closestMultiple(width, size, n, limit) {
if(n > limit) {
return {m: width/size, s:size};
}
if((width % (size+n)) == 0) {
return {m: width / (size+n), s: size+n};
} else if((width % (size-n)) == 0) {
return {m: width / (size-n), s: size-n};
}
return closestMultiple(width, size, n+1, limit);
}
var wcm = closestMultiple(windowWidth, size, 0, 5);
var hcm = closestMultiple(windowHeight, size, 0, 5);
// Calculate the number of cells we can fit in the width
//and height (there will be extra space)
var w = Math.floor(wcm.m);
var h = Math.floor(hcm.m);
console.log(wcm);
console.log(hcm);
// Calculate the extra space
var widthDiff = windowWidth % wcm.s;
var heightDiff = windowHeight % hcm.s;
// Add the needed amount of height and width to each cell to fill the window
var widthSize = Math.floor(wcm.s + widthDiff / w);
var heightSize = Math.floor(hcm.s + heightDiff / h);
//NOW, convert pixels to percentages.
var widthPercent = widthSize / windowWidth * 100;
var heightPercent = heightSize / windowHeight * 100;
// Begin to alter the DOM
var parentDiv = document.createElement('div');
parentDiv.className = 'grid';
parentDiv.style.height = windowHeight + 'px';
parentDiv.style.width = windowWidth + 'px';
for(var x = 0; x < w*h; x++) {
var cellDiv = document.createElement('div');
cellDiv.className = 'cellDiv';
cellDiv.style.height = heightPercent + '%';
cellDiv.style.width = widthPercent + '%';
parentDiv.appendChild(cellDiv)
}
document.body.appendChild(parentDiv);