I'm moving to a new blog. A blog that's all about my adventures as a traveling designer and wonder seeker.

So I got faced with a problem as I was coding a project up and didn’t like the solutions online that all said to use either tables or browser specific hacks. So how to vertically align images in a div with some simple code?

Now to move on to the code… Lets say you have blog posts and they have an option for the user to upload images… How to make it bulletproof? You can set the max size, and if the user uploads images that are smaller, you can use this script to make sure images will always be centered… So put your images in a wrapper with a fixed width and height of the maximum image size, that’s where we subtract the image height from that dimension, so lets say you want your images to be maximum 120x120px. Make a 120x120px container and display the img tags in that container, now in the javascript bellow, just change out your container height.

Now this script is ready for use on the document ready statement, it will loop through each of the images with your desired class, and apply a padding based on its dimensions, and hey presto, perfect vertically aligned images.

/* Vertical Image Align */
$('img.attachment-image').each(function() {
    var h = $(this).height();
    var height = (120-h)/2;
    if (h < 120) {
        $(this).css('margin-top', height + "px");
    }else{
            $(this).css('margin-top', '0px');
        }
});

Join The Discussion (5 Comments)

Submit Comment
avatar

Zan

I tried almost everything, some tricks worked but only in specific browsers, some didn't... So this is my way of doing it, I'm not saying this is the best way, but its simple, and works in the all browsers that have js :)

Posted 6 years ago
avatar

knightkiddo

As always, nice things here. This tips is really simple & cool. Thanks to you.

Posted 6 years ago
avatar

Chris Gadzinski

Hey would it have also worked to make the image the background image of the enclosing div setting the position to 50% 50% ?? I like this method just wondering if a pure css option was avail.

Posted 6 years ago
avatar

Zan

That was one of the reasons I did this, that and the countless table cell tricks didn't work.

Posted 6 years ago
avatar

Will

I don't understand, why don't you just use line-height 100% to align?

Posted 6 years ago