Equalising box baselines with Javascript

Aug 22 2006

A while ago I wrote about creating equal height boxes using Javascript, and occasionally I find myself referring back to that article when I need the technique for a project.

Recently I added it to a layout only to find it didn’t have quite the effect I intended. One of the boxes had a top-margin applied, so equalising the box heights meant that their bottoms were still out of line – I needed a means of lining up the baseline of the boxes.

Here are the two new functions and one extra variable I added to the BoxHeights object literal from the previous article:

  1. maxb: 0,
  2.  
  3. baseline: function() {
  4. this.num = arguments.length;
  5. for (var i=0;i<this.num;i++) if (!$(arguments[i])) return;
  6. this.boxes = arguments;
  7. this.findBase();
  8. for (var i=0;i<this.num;i++) $(arguments[i]).style.height = (this.maxb - $(arguments[i]).offsetTop) + "px";
  9. },
  10.  
  11. findBase: function() {
  12. var bottoms = new Array();
  13. for (var i=0;i<this.num;i++) {
  14. if (navigator.userAgent.toLowerCase().indexOf('opera') == -1) {
  15. bottoms.push($(this.boxes[i]).offsetTop + $(this.boxes[i]).scrollHeight);
  16. } else {
  17. bottoms.push($(this.boxes[i]).offsetTop + $(this.boxes[i]).offsetHeight);
  18. }
  19. }
  20. bottoms.sort(this.sortNumeric);
  21. this.maxb = bottoms[this.num - 1];
  22. }
  23.  
  24. Download this code: /code/baseline-1.txt

They are roughly equivalent to the existing equalise() and maxheight() functions, but instead of working out the height they calculate (through the power of simultaneous equations – the one thing I learned in school) which box has the lowest baseline, and then adjust the heights of each box so the baselines are the same.

Again, here’s a simple demonstration. Code is tested in IE6, FF1+, Safari 2, Opera 9.

Filed under: Javascript.

Digg this article

Bookmark this article with del.icio.us

Previously: Things you notice on dial-up

Next: Review: NewsGator Online


Comments