tags:

views:

200

answers:

1

I created a plugin to bottom-align a element. In it's simplest form I did this:

  1. Get height of outerElement (DIV)
  2. Get height of current element
  3. result = outerHeight - height of current element
  4. sett CSS attribute 'top' = result.

And it works... in Firefox and IE8, but not in Opera or Google Chrome.

I'm guessing it has to do with borders, padding and margin. So what do I have to do in order to make it work cross-browser?

UPDATE
Code has been revised and is working now.

(function($){
    $.fn.alignBottom = function() 
    {

        var defaults = {
            outerHight: 0,
            elementHeight: 0
        };

        var options = $.extend(defaults, options);
        var bpHeight = 0; // Border + padding

        return this.each(function() 
        {
            options.outerHight = $(this).parent().outerHeight();
            bpHeight = options.outerHight - $(this).parent().height();
            options.elementHeight = $(this).outerHeight(true) + bpHeight;


            $(this).css({'position':'relative','top':options.outerHight-(options.elementHeight)+'px'});
        });
    };
})(jQuery);

The HTML could look something like this:

div class="myOuterDiv">
    <div class="floatLeft"> Variable content here </div>
    <img class="bottomAlign floatRight" src="" /> </div>
</div>

and applying my jQuery plugin:

jQuery(".bottomAlign").alignBottom();
+1  A: 

You probably need to look into the outerHeight() jQuery method:

options.outerHight = $(this).parent().outerHeight();
options.elementHeight = $(this).outerHeight( true ); // Include margins

You also probably need to play with .position().top which is the distance the element already is moved away from the top of the containing element:

var new_top = $(this).parent().outerHeight() - $(this).outerHeight() - $(this).position().top;

Another approach

A couple things about position:relative. Elements positioned like this will take up space, but can be shifted in any direction. Note that shifting them does not change where they took up space, only where the element displays.

About position:absolute. An absolutely positioned element does not take up space, but needs to be inside an element that has position (i.e. position:relative)

So, in straight CSS:

.myOuterDiv { position: relative }
.bottomAlign { position: absolute; bottom: 0 }

But note that any position it used to take up (i.e. because of the float right) it will no longer take up.

Doug Neiner
Ah, thanks. That owkred. The only problem with this solution is that half og the inner element is pushed outside the outer div. To fix this, I just multiplied the elementHeight with 2 - to make it stay inside outer div.
Steven
Of course, that will only work for my image which is only 30 px high.
Steven
@Steven I added to my answer, hope it points you in the right direction.
Doug Neiner
I have revised my code to reflect working plugin. Thanks for your help!
Steven