Skip to content Skip to sidebar Skip to footer

Dithering Child Elements' Dimensions To Fill A Parent Element

Say I have a parent div with width 500px. It has 13 child elements that should fill its width. If I give each child element a width of 500 / 13 = 38.46... pixels, the browser will

Solution 1:

I'd suggest you just do everything with integer math yourself. You can then calculate what the uneven amount is and then decide how you want to distribute it across the elements. My supposition is that the least noticeable way to distribute the extra pixels would be to keep as many like width elements next to each other as possible.

One way of doing that would to calculate how many extra pixels N you have and then just give each N elements starting from the left one extra pixel. If you were worried about things not being centered, you could allocate the first extra pixel to the far left object, the second extra pixel to the far right, the third extra pixel to the 2nd from left, the fourth extra pixel from the 2nd from right, etc... This would have one more boundary between dissimilar width objects, but be more symmetric than the first algorithm.

Here's some code that shows how one could put the extra pixels on the end elements from outside in:

function distributeWidth(len, totalWidth) {
    var results = new Array(len);
    var coreWidth = Math.floor(totalWidth / len);
    var extraWidth = totalWidth - (coreWidth * len);
    var w,s;
    for (var i = 0; i < len; i++) {
        w = coreWidth;
        if (extraWidth > 0) {
            w++;
            extraWidth--;
        }
        if (i % 2 == 0) {
            s = i/2;               // even, index from front of array
        } else {
            s = len - ((i+1)/2);   // odd, index from end of array
        }
        results[s] = w;
    }
    return(results)
}

And here's a fiddle to see it in action: http://jsfiddle.net/jfriend00/qpFtT/2/

Post a Comment for "Dithering Child Elements' Dimensions To Fill A Parent Element"