2012-03-12 9 views
2

私はdivのX量を持っており、すべて特定の高さと幅に設定されています。これらの中にはイメージがあり、すべてサイズが異なります。私は画像の高さを見つけ出し、2で割ってそれを余白のトップ値として設定して、それが理にかなっていればすべての画像が中央にくるようにしたいのですか?アイブ氏はマージントップ=要素jQueryの50%

http://jsfiddle.net/R8QUL/1/

答えて

6

あなたはここにこの

$(document).ready(function() { 

    $('.box img').each(function() { 
     var $this = $(this); 
     var parentHeight = $this.parent().height(); 
     var thisHeight = $this.height(); 
     var topmargin = (parentHeight - thisHeight)/2; 
     $this.css("margin-top", topmargin); 
    }); 
}) 

フィドルhttp://jsfiddle.net/R8QUL/6/

+1

を追加これには「パディング」が含まれており、それは視覚的にボックス要素の内部の一部です。 Liamがしようとしていると判断して、おそらくこれも考慮しなければならないものかもしれないと私は想像しています。 –

2
$(document).ready(function(){ 

    var boxheight = $('.box').height(); 

    $('.box img').each(function(i){ 
      var topmargin = (boxheight - $(this).height())/2 
      $(this).css("margin-top", topmargin); 
    }); 



}) 

ライブのような何かができる...フィドルだけそれについて移動する方法がわからないイム作ってみましたデモ

http://jsfiddle.net/R8QUL/5/

1

は、ここで私はいくつかの画像をロードするために時間がかかるので、まだの幅や高さを持っていないこと

$(document).ready(function(){ 
    $('.box img').each(function() { 
     $(this).css("margin-top", $(this).parent().height()/2-$(this).height()/2); 
    }); 
});​ 

FIDDLE

0

を行うだろう方法です。この問題を解決するには、setTimeoutを使用します。

$(document).ready(function(){ 
    $.each($('.box'), function(){ 
     centerImage($(this)); 
    }); 
}); 

function centerImage(box){ 
    var imgWidth = $(box).find('img').width();  
    var imgHeight = $(box).find('img').height(); 

    if(imgWidth > 0 && imgHeight > 0){ 
     $(box).find('img').css('margin-top', ($(box).height() - imgHeight)/2); 
    } else { 
     setTimeout(function(){ centerImage(box); }, 100); 
    }  
} 

http://jsfiddle.net/7EDSF/

1

あなたは純粋なCSSのソリューションに興味があるなら:http://jsfiddle.net/R8QUL/11/
ちょうど `.innerHeightは()`あまりにもうまくいくかもしれないことを注目に値するかもしれ

.box 
    line-height: 225px; 
} 

.box img { 
    display: inline-block; 
    vertical-align: middle; 
} 
+0

今すぐ書く私はまたこの解決策を働いています:) – sandeep