The code below works with the jQuery collection.
For each element in the collection, the width is changed to minimize the difference between the widest and thinnest client rectangles (using getClientRects ).
The code ensures that the number of client errors does not change. This prevents the element from expanding or enlarging.
getClientRects returns one rectangle for block level elements. For this reason, the code adds span to the element to preserve its HTML content, and the logic is based on the fact that span client rects. (Then the span is removed.)
function balance(el) { el.each(function() { var temp= $('<br><span>'+$(this).html()+'</span>').appendTo(this), sp= $(this).find('span')[0], num= sp.getClientRects().length; for(var w=$(this).width(), i=10, best=10, delta=9999 ; i <= w ; i++) { $(this).width(i); var cr=sp.getClientRects(); if(cr.length > num) continue; for(var min=9999, max=0, j=0 ; j < cr.length; j++) { min= Math.min(min, cr[j].width); max= Math.max(max, cr[j].width); } if(max-min < delta) { delta= max-min; best= i; } } $(this).width(best); temp.remove(); }); };
Working script
source share