I have created a script that slides images. Each image is contained in a “slide” div. What I want to do is vertically align each individual image using jquery. Currently am I using:
$('.slide img').each(function() {
var image_height = $(this).height();
var height_margin = (image_height/2)*-1;
$('.slide img').css('margin-top', height_margin);
$('.slide img').css('top', 50%);
$('.slide img').css('height', image_height);
});
What I’ve noticed is that it applies the first height and margin from the first image to ALL of the <div class"slide"></div> tags. Also: <div class"slide"></div> has the constant height of 600px.
Not every image is the same and I want it to be dynamic… Any thoughts?
You shouldn’t use
$('.slide img')inside the.eachloop, because this selector will change all styles. Currently, you’re applying the settings of the last image to all images. Another error in your code: You have forgotten to quote50%.Your code can be optimized even more: