私はdivのX量を持っており、すべて特定の高さと幅に設定されています。これらの中にはイメージがあり、すべてサイズが異なります。私は画像の高さを見つけ出し、2で割ってそれを余白のトップ値として設定して、それが理にかなっていればすべての画像が中央にくるようにしたいのですか?アイブ氏はマージントップ=要素jQueryの50%
2
A
答えて
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);
});
})
2
$(document).ready(function(){
var boxheight = $('.box').height();
$('.box img').each(function(i){
var topmargin = (boxheight - $(this).height())/2
$(this).css("margin-top", topmargin);
});
})
ライブのような何かができる...フィドルだけそれについて移動する方法がわからないイム作ってみましたデモ
1
は、ここで私はいくつかの画像をロードするために時間がかかるので、まだの幅や高さを持っていないこと
$(document).ready(function(){
$('.box img').each(function() {
$(this).css("margin-top", $(this).parent().height()/2-$(this).height()/2);
});
});
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);
}
}
1
あなたは純粋なCSSのソリューションに興味があるなら:http://jsfiddle.net/R8QUL/11/
ちょうど `.innerHeightは()`あまりにもうまくいくかもしれないことを注目に値するかもしれ
.box
line-height: 225px;
}
.box img {
display: inline-block;
vertical-align: middle;
}
+0
今すぐ書く私はまたこの解決策を働いています:) – sandeep
関連する問題
- 1. フリーロールされていない要素で動作しないマージントップ
- 2. jQueryの - 要素
- 3. jQueryの要素
- 4. マージントップの問題
- 5. 空白で50%のdivを2つ:フレックスコンテナ内のnowrap要素
- 6. CSS:幅100%の子要素の幅がわずか50%
- 7. jquery要素コレクションのswitch要素位置
- 8. jquery mobile - フォーム要素の内部要素
- 9. 一度に50個以上の要素をループする(matlab)
- 10. jQueryの - 各要素
- 11. jQueryのselect要素
- 12. jQueryのデータ要素
- 13. のjQuery:要素ID
- 14. は、jQueryの要素
- 15. ターゲット要素 - jQueryの
- 16. のjQuery&param要素
- 17. jQueryの:子要素
- 18. 空のjquery要素
- 19. jQueryの「ハイライト」要素
- 20. 要素のjquery order
- 21. jquery要素のトップ
- 22. jqueryのドラッグ要素
- 23. jQueryのテーブル要素
- 24. jQueryのは、要素
- 25. jquery要素クロスフェードプラグイン
- 26. jquery append要素
- 27. jqueryカラーピッカーホバー要素
- 28. jQuery UI要素とDojo(Dijit)フォーム要素
- 29. WPF相当のマージントップ?
- 30. は、CSSマージントップIE7
を追加これには「パディング」が含まれており、それは視覚的にボックス要素の内部の一部です。 Liamがしようとしていると判断して、おそらくこれも考慮しなければならないものかもしれないと私は想像しています。 –