Flushify

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!

Flushify

One thought on “Flushify

  1. […] I was the sole front-end developer on this project. Some small JavaScript flourishes helped it be more fun than your everyday brochure site. I finally took the time to develop a jQuery extension for making the final “column” of a list of floated elements flush with the right edge of the container. I call it Flushify. […]

Leave a Reply

Your email address will not be published.