jQuery: centering a lightbox without a stated height

CSS developers know an old technique to center a box both horizontally and vertically within a container. The top and left properties will be set to 50% and the margin-top and margin-left properties will be set to the half of the total height and width of the box, respectively. This technique turns out to be really useful with jQuery lightboxes. Let's see why.

Our lightboxes have a stated width but no stated height:

div.box {
    border: 1px solid #333;
    position: absolute;
    width: 20em;
    padding: 1em;
    line-height: 1.3;
    background: #000;
    color: #fff;
    border-radius: 10px;
    display: none;
}

We can apply the aforementioned CSS technique to these elements with jQuery, as follows:

var LightBox = {
	// other methods
	positionBoxes: function() {

        $('div.box').each(function() {
            var $box = $(this);
            $box.css({
                top: '50%',
                left: '50%',
                marginTop: '-' + Math.round($box.outerHeight() / 2) + 'px',
                marginLeft: '-' + Math.round($box.outerWidth() / 2) + 'px'
            });

        });

    },
    // other methods
};

We've used the outerHeight() and outerWidth() methods to assign the correct values for the top and left margin to each box. Even though the final result is not pixel-perfect, it's a good starting point to make further adjustments to the returned values.

You can see the complete demo below.

Demo

Live demo

Back to top