javascriptcsslayoutgriddrawing

Drawing a grid using CSS


I'm looking for a way to draw a grid (i.e. http://www.artlex.com/ArtLex/g/images/grid.gif) inside of a div, using CSS (and JS if necessary). It feels like it should be relatively straight forward, but I haven't been able to figure it out. Any advice would be greatly appreciated.

Thank you in advance, Lenny


Solution

  • 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 window.innerWidth to return accurate numbers fixed that:

    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('');