2

I need to improve a jquery script which snaps the height of image containers to a baseline grid. I want to make it work during window resize.

So far, I applied the following to the image containers which have overflow set to hidden. Some of it was inspired by questions asked here and here.

/* Updates height on $(window).load(function(){}); */
$(window).load(function(){

    /* Adjust media container heights and image margins */
    function containerHeight(){
        var targetContainer = 'div.media';
        $(targetContainer).each(function(){
            var targetHeight = Math.round($(this).height() / 20) * 20 - 8;
            if($(this).height() < targetHeight){
                var newHeight = targetHeight - 20;
            }else{
                var newHeight = targetHeight;
            }
            $(this).css({
                'height': newHeight
            });
        });
        $(targetContainer).children('img').each(function(){
            $(this).css({
                'margin-top': Math.round(($(this).parent(targetContainer).height() - $(this).height()) / 2 )
            });
        });
    }
    containerHeight();
    /* Does not update height on $(window).bind('resize', function(){}); with <body class="full"> */
    $(window).bind('resize', function(){
        containerHeight();
    });

});

However, my pastie at http://pastie.org/2846491 only works for fixed-width containers.

I need to make this work for fluid container widths/heights, during/after window resize and mobile orientation:portrait/landscape changes, while keeping things on the baseline grid.

Any pointers on how I should approach this? Please help!

Community
  • 1
  • 1
Flo
  • 31
  • 3

1 Answers1

0

I had this problem recently, and jury-rigged a solution. Not the most elegant/efficient solution, but certainly workable:

var fontSize = 20;
var lineHeight = 28;

$(window).resize(function() {
    $('img').each(function() {
        var heightDif = $(this).outerHeight();
        $(this).css('margin-bottom', fontSize + heightDif % lineHeight);
    });
});
$('img').load(function() { $(window).resize(); });

The code fires whenever the window is resized, and calculates the difference between the image height and the next lowest baseline. It then adds the difference to the bottom margin. The event first fires on img load (here's an opportunity for better efficiency).

I hope this helps; if you have any improvements that would make it better, I'd love to know so I could implement them in my code!