Search code examples
jqueryalignment

Trying to use jQuery to horizontally distribute elements of different sizes in a <div>


I'm trying to use jQuery to space these elements apart equally. As you can see, I'm totaling up the widths of the objects and subtracting by the width of the surrounding DIV to find the empty space. Then I divide that empty space and space out each element by that amount (via right margin). Here is the JSFiddle: http://jsfiddle.net/spaceninja/baQNA/

My question is (note: I am using this as a learning opportunity because I know there are other methods of doing this) why must I subtract 4 in the following line for it to work? I thought doing the Math.floor would round it down enough, but there are still approx 4 pixels that are breaking this down to the next line. If you take the -4 out of the following line, it breaks and I don't know why.

var spacer = (Math.floor(remaining / 4) -4 );

Here is the HTML:

<div>
    <span>Short</span>
    <span>A Very Very Long One Is Right Here</span>
    <span>Short</span>
    <span>Short</span>
    <span>Short</span>        
</div>

And here is the jQuery:

var measurements = 0;
for (var i=0; i<=4; i++) {
    measurements += $('span').eq(i).width();
}
var totalWidth = $('div').width();
var remaining = 0;
remaining = totalWidth - measurements;
var spacer = (Math.floor(remaining / 4) -4 );
for (var i=0; i<=3; i++) {
    $('span').eq(i).css('margin-right', spacer);
}

Solution

  • it's cause of space characters between your spans

    <div><span>Short</span><span>A Very Very Long One Is Right Here</span><span>Short</span><span>Short</span><span>Short</span></div>
    

    http://jsfiddle.net/r043v/baQNA/7/