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 allign 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 buletproof? 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 allways 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 alligned images.
1 2 3 4 5 6 7 8 9 10 | /* Vertical Image Allign */ $('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'); } }); |

