Drawing a grid using CSS
Here's a simple solution using jQuery. This script will try to fill in as many grid element as possible without overflowing. The function accepts a single parameter, which defines the size of the grid.
function createGrid(size) {
var ratioW = Math.floor($(window).width()/size),
ratioH = Math.floor($(window).height()/size);
var parent = $('<div />', {
class: 'grid',
width: ratioW * size,
height: ratioH * size
}).addClass('grid').appendTo('body');
for (var i = 0; i < ratioH; i++) {
for(var p = 0; p < ratioW; p++){
$('<div />', {
width: size - 1,
height: size - 1
}).appendTo(parent);
}
}
}
It also requires a simple CSS style:
.grid {
border: 1px solid #ccc;
border-width: 1px 0 0 1px;
}
.grid div {
border: 1px solid #ccc;
border-width: 0 1px 1px 0;
float: left;
}
See a simple demo here: http://jsfiddle.net/yijiang/nsYyc/1/
Here's one using native DOM functions. I should also change the initial ratio calculation to use DOM functions but I cannot for the life of me get fixed that: window.innerWidth
to return accurate numbers
function createGrid(size) {
var ratioW = Math.floor((window.innerWidth || document.documentElement.offsetWidth) / size),
ratioH = Math.floor((window.innerHeight || document.documentElement.offsetHeight) / size);
var parent = document.createElement('div');
parent.className = 'grid';
parent.style.width = (ratioW * size) + 'px';
parent.style.height = (ratioH * size) + 'px';
for (var i = 0; i < ratioH; i++) {
for (var p = 0; p < ratioW; p++) {
var cell = document.createElement('div');
cell.style.height = (size - 1) + 'px';
cell.style.width = (size - 1) + 'px';
parent.appendChild(cell);
}
}
document.body.appendChild(parent);
}
createGrid(10);
It's basically a direct translation of the jQuery code. If you need even more performance you can switch to generating the boxes using strings pushed to an array:
arr.push('<div style="width:', (size - 1), 'px;height:', (size - 1), 'px;"></div>');
then at the end
parent.innerHTML = arr.join('');
Here is a simple CSS-only solution, using linear gradients:
html,
body,
.grid {
height: 100%;
width: 100%;
margin: 0;
}
.grid {
background-image:
repeating-linear-gradient(#ccc 0 1px, transparent 1px 100%),
repeating-linear-gradient(90deg, #ccc 0 1px, transparent 1px 100%);
background-size: 71px 71px;
}
<div class="grid"></div>