
While I don’t ordinarily recommend resorting to JavaScript to resolve presentation problems, there are some occasions where a design is not flexible and a pure CSS solution is just out of reach. One such situation that seems to come up regularly is achieving “justified” alignment for floated list elements. If such a list is inside of a container, which it generally is, the margin between the list elements will be a problem for the the elements at the end of each “row”. Unfortunately, there isn’t yet a pseudo-class “last-child-this-row” or “in-the-last-column”.
My solution was to create a tiny little plugin to achieve this. It basically measures the width of the container, measures the width of a representative list item, figures out how many of those fit into each row, and then gives each list item at row’s end a special class to be manipulated via CSS.
$.fn.flushify = function() {
return this.each(function(){
$('li',this).removeClass('row-end');
var w = $(this).width();
var x = $('li:first-child', this).innerWidth();
var ender = Math.round(w/x);
$('li:nth-child('+ender+'n)',this).each(function(){
$(this).addClass('row-end');
});
});
}
Obviously, I could have just as easily done this for row-start if my list items’ margin was on the left instead of the right.
Perhaps there are better ways to achieve this effect that I’ve overlooked. If you know of one, weigh in!