const gridSize = 8 const offsetRef = document.querySelector('.mb-center') const gridColor = 'rgba(8,22,36,.1)' /* Use something like the following in a stylesheet to improve the grid: .mb-grid > div > div:nth-child(3n + 1) { background-color: rgba(8,22,36,.2) !important; } */ function renderGrid(e) { // math const offsetLeft = offsetRef.offsetLeft % gridSize const numCols = Math.floor((document.documentElement.clientWidth - offsetLeft % gridSize) / gridSize) const numRows = Math.floor(Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) / gridSize) // grid const grid = document.createElement('div') grid.className = 'mb-grid' Object.assign(grid.style, { left: offsetLeft +'px', height: '100%', position: 'absolute', top: 0, width: (numCols - 1) * gridSize + 1 +'px', }) // cols const cols = document.createElement('div') cols.className = 'mb-grid-cols' Object.assign(cols.style, { display: 'flex', height: '100%', left: 0, position: 'absolute', top: 0, }) for (let c = 0; c < numCols; c++) { let col = document.createElement('div') Object.assign(col.style, { backgroundColor: gridColor, marginRight: gridSize - 1 +'px', width: '1px', }) cols.appendChild(col) } grid.appendChild(cols) // rows const rows = document.createElement('div') rows.className = 'mb-grid-rows' Object.assign(rows.style, { // display: 'flex', width: '100%', }) for (let r = 0; r < numRows; r++) { let row = document.createElement('div') Object.assign(row.style, { backgroundColor: gridColor, height: '1px', marginBottom: gridSize - 1 +'px', }) rows.appendChild(row) } grid.appendChild(rows) // remove existing grid and insert with new maths const g = document.body.querySelector('.mb-grid') if (g) g.remove() document.body.appendChild(grid) // done console.log('%c⚏ '+ gridSize +'pt grid rendered with '+ numCols +' columns and '+ numRows +' rows', 'color:#0cd', e) } // only fire a few times per second during resize function debounce(func, wait = 200) { let timeout; return (...args) => { clearTimeout(timeout) timeout = setTimeout(() => { func.apply(this, args) }, wait) } } const debounced = debounce(renderGrid) // fire when ready window.addEventListener('resize', debounced) window.addEventListener('load', renderGrid) // toggle with 'g' key document.addEventListener('keypress', (e) => { if (e.which === 103) { let toggle = document.querySelector('.mb-grid') toggle.style.display = toggle.style.display === 'none' ? 'block' : 'none' } })