Search code examples
javascripthtmlcssalignment

Arranging Images Randomly In Order


I have a list of images with various sizes and I have to show them all in a page. I want to arrange them in such a way that no white spaces are shown between images on oneline and the image on the next line. Anyways I can achieve this using CSS and Javascript, ??

Following is the example on jsFiddle.

http://jsfiddle.net/zHxPT/1/


Solution

  • If you're willing to have the images overlap each other you can have minimum gap between them using client side code to position the items dynamically:

    window.onload = function() {
        var oList = document.getElementById("liParent")
        var arrItems = oList.getElementsByTagName("li");
        var totalWidth = parseInt(oList.style.width, 10);
        var curLeft = 0;
        var curTop = 0;
        var arrHeights = new Array();
        var colIndex = 0;
        for (var i = 0; i < arrItems.length; i++) {
            var oCurItem = arrItems[i];
            var oImage = oCurItem.getElementsByTagName("img")[0];
            oCurItem.style.position = "absolute";
            var curWidth = oImage.offsetWidth;
            var curHeight = oImage.offsetHeight;
            if (curLeft + curWidth > totalWidth) {
                curLeft = 0;
                colIndex = 0;
            }
            if (colIndex < arrHeights.length)
                curTop = arrHeights[colIndex];
            oCurItem.style.left = curLeft + "px";
            oCurItem.style.top = curTop + "px";
            arrHeights[colIndex] = (curHeight + curTop);
            curLeft += curWidth;
            colIndex++;
        }
    }
    

    Updated jsFiddle: http://jsfiddle.net/zHxPT/2/