Steven
Steven

Reputation: 19425

How can I calculate the height of an element cross-browser using jQuery?

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();

Upvotes: 2

Views: 1720

Answers (1)

Doug Neiner
Doug Neiner

Reputation: 66191

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.

Upvotes: 1

Related Questions