开发者

How do I vertically align mulitple images with different heights using jQuery?

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 .each loop, 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 quote 50%.

$('.slide img').each(function() {
    var $this = $(this);
    var image_height = $this.height();
    var height_margin = (image_height/2)*-1;
    $this.css('margin-top', height_margin);
    $this.css('top', '50%');    
    $this.css('height', image_height);    
});

Your code can be optimized even more:

$('.slide img').each(function() {
    var $this = $(this);
    var image_height = $this.height();
    var height_margin = -image_height / 2
    $this.css({'margin-top', height_margin,
               'top', '50%',  
               'height', image_height
              });    
});


If the .slide container has a constant height you could apply display:block and margin:auto 0; to .slide img in CSS to achieve the same effect...no JS calculations required.


OK I have a solution, first make the containing DIV's line-height matches the height of your tallest image, then use vertical-align:middle in a class which you apply to all images, make sure the images are set to display:inline though or it wont work.

div.container {line-height:300px;} /*or whatever that may be, then*/
img.slides {vertical-align:middle;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜