The problem we’re going to solve today is centering an image horizontally and vertically inside of a container. This won’t be just a simple centering  of elements but we’re going to write a script that will resize the photo to fill up the container and keep it’s aspect ratio preserved.

The CSS way

There are at least a few methods that allow you to center image inside of a container with CSS but none solves a problem in some general way. With CSS you can use line-height attribute, display:table trick, negative margins and  absolute positioning etc. but those are not enough if you want to fill up container with an image.

The JavaScript way

The only way I could find was to use some of the capabilities of JavaScript and jQuery to fulfil requirements set. But how to make it work? How to center an image with jQuery? Here is the code:

(function ($, undefined) {
    $.fn.centerfill = function () {
        return this.each(function () {
            var iWidth = $(this).width();
            var iHeight = $(this).height();

            var parent = $(this).parent();
            parent.css('position', 'relative');
            var pWidth = $(parent).width();
            var pHeight = $(parent).height();
            var scaleW = iWidth / pWidth;
            var scaleH = iHeight / pHeight;
            var scale = Math.min(scaleW, scaleH);
            var rWidth = iWidth / scale;
            var rHeight = iHeight / scale;
            $(this).width(rWidth).height(rHeight).css({
                'position': 'absolute',
                'left': (rWidth - pWidth) / -2,
                'top': (rHeight - pHeight) / -2
            });
        });
    };
})(jQuery);

Example

It’s damn easy to use it.

The Simple

You’ll have to create a container that has defined dimensions:


<div style=”width: 160px; height: 90px;: ”>
    <img src=”image/path.jpg”  class=”center”/>
</div>

and then just invoke:


(function () {
    $(“img.center”).centerfill();
}); 

Image will be resize and fill up the whole container and centere against it.

Combining with jquery.lazyload.js

You can also make use of jquery.centerfill.js with jquery.lazyload.js. Define you html

 <div style=”width: 160px; height: 90px;: ”> <img src=”some/small/dot.gif” data-original=”image/path.jpg”  class=”lazy”/> </div>

jQuery LazyLoad provides a callback that is invoked after the image is loaded so you can center your image there like this


(function () {
    $("img.lazy").lazyload({ 
        effect : 'fadeIn',
        load : function() { 
           $(this).centerfill(); 
        }
     });

Conclusion

Have fun using it. If you would like to contribute to this project please visit my GitHub repository.
This piece of script is licensed under MIT Open Source license.

Reference

“6 Methods For Vertical Centering With CSS” http://www.vanseodesign.com/css/vertical-centering/ (01/01/2012)
“JQuery Lazy Load” http://www.appelsiini.net/projects/lazyload