views:

66

answers:

5

I need to position an element in the exact centre of the page (using fixed positioning) and need to calculate the expected size. For example I would add HTML like this:

<div class="window" style="left: X; top: Y">
    <h3 class="title">Title</h3>
    <img src="file.jpg" width="300" height="200" />
    <div class="controls">Some stuff</div>
</div>

The width will be the image width plus some padding. I want to determine what the height of the element will be by getting the styles from the stylesheet, then calculate the correct position, then write the HTML with the right styles.

A: 

you can get width and height using width() and height()

so $('.window').height() will return the computed height of the element in your case.

David
A: 

You can use CSS:

.window {
  margin: 0 auto;
}
dmitrig01
This won't work for ie6
Luca Matteis
"This won't work for ie6" *sigh*.....story of my life....:D
CrazyJugglerDrummer
Works exactly the same in IE6 as other browsers (in standards mode). But it doesn't do vertical height, which is the key here.
DisgruntledGoat
Oh whoops, misread your question, sorry.
dmitrig01
+2  A: 

With jQuery, you want to use the outerHeight and outerWidth functions.

Without jQuery, you want to use offsetHeight and offsetWidth DOM properties.

Note that these both include the padding and border in their calculations, whereas jQuery height and width do not. Optionally, outerHeight and outerWidth can be made to include margin, but offsetHeight and offsetWidth cannot.

Mike
But how do I get the values before inserting the element into the document?
DisgruntledGoat
Indeed you *cannot* do that. Reason being different documents can have different style rules. You can only measure a DOM element after it has been added to a DOM document. Additionally, its CSS `display` must be anything other than `none`, but its visibility can be `hidden`.
Mike
Actually, let me take that back. You certainly could do it, since standards-compliant browsers (and MSIE, via different properties) allow you to programatically access style sheet rules, but you would essentially have to write your own CSS parser to accomplish it.
Mike
+1  A: 

You can only tell once it's been added to the document (that is, you can't tell the expected size and you won't be able to do it server-side).

So, in Javascript, set the visibility to hidden, add it to the document, check its outerHeight or with jQuery call $('.window').height(), reposition as needed, and then change visibility back to visible.

...or, use this plugin:

jQuery(function($) {
    $.fn.vCenter = function(options) {
        var empty = {},
            defaults = {
                allowNegative : false,
                relativeToBody : true
            },
            settings = $.extend(empty, defaults, options)
        ;

        var isVisible = this.is(":visible");
        if (!isVisible) {
            this.css({visibility : "hidden"}).show();
        }
        if (settings.relativeToBody && this.offsetParent().get(0).nodeName.toLowerCase() != "body") {
            this.appendTo(document.body);
        }
        var pos = {
            sTop : function() {
                return window.pageYOffset || $.boxModel && document.documentElement.scrollTop || document.body.scrollTop;
            },
            wHeight : function() {
                if ($.browser.opera || ($.browser.safari && parseInt($.browser.version, 10) > 520)) {
                    return window.innerHeight - (($(document).height() > window.innerHeight) ? getScrollbarWidth() : 0);
                } else if ($.browser.safari) {
                    return window.innerHeight;
                } else {
                    return $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
                }
            }
        };
        return this.each(function(index) {
            if (index === 0) {
                var $this = $(this),
                    $w = $(window),
                    topPos = ($w.height() - $this.height()) / 2 + $w.scrollTop()
                ;
                if (topPos < 0 && !settings.allowNegative) topPos = 0;

                $this.css({
                    position: 'absolute',
                    marginTop: '0',
                    top: topPos //pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2)
                });
                if (!isVisible) {
                    $this.css({visibility : ""}).hide();
                }
            }
        });
    };
    $.fn.hCenter = function(options) {
        var empty = {},
            defaults = {
                allowNegative : false,
                relativeToBody : true
            },
            settings = $.extend(empty, defaults, options)
        ;

        if (settings.relativeToBody && this.offsetParent().get(0).nodeName.toLowerCase() != "body") {
            this.appendTo(document.body);
        }
        return this.each(function(index) {
            if (index === 0) {
                var $this = $(this),
                    $d = $(document),
                    leftPos = ($d.width() - $this.width()) / 2 + $d.scrollLeft()
                ;
                if (leftPos < 0 && !settings.allowNegative) leftPos = 0;
                $this.css({
                    position: "absolute",
                    left: leftPos
                });
            }
        });
    };
    $.fn.hvCenter = function(options) {
        return this.vCenter(options).hCenter(options);
    };
});

Usage:

$('.window').hvCenter();  // horizontal and vertical center
nickf
A: 

Have you tried this pure CSS way of centering an image in a box?

Luca Matteis