0

これを自分で何時間も整理しようとした後、私よりもよく知っている人に頼る必要があると感じています. 親 div 内で子 div を中央に配置する機能があります。それはすべて機能しますが、唯一の問題は子divのサイズが変わることです。そのため、この関数をすべてのdivに個別に適用する方法が必要です。

ここに私のコードがあります

HTML

<div class="outer">
<div class="inner">short text in here</div>
</div>

<div class="outer">
<div class="inner">some text in here more text here that is longer. This is longer</div>
</div>

CSS

.outer{background:#eee;height:150px;width:150px;margin-bottom:20px;}
.inner{width:130px;padding:10px;text-align:center;}

ジャバスクリプト

$(document).ready(function(){
var inner = $('.inner'),
ht = inner.height();

inner.css({'position':'absolute','top':'50%','margin':-ht/2+'px 0 0 0'});
});

http://jsfiddle.net/AMNVY/

4

2 に答える 2

1

これはうまくいきますか?

私がしたのはCSSを編集することだけでした:

.outer{
    background:#eee;
    height:150px;
    width:150px;
    margin-bottom:20px;
    display: table;
}
.inner{
    width:130px;
    padding:10px;
    text-align: center;
    vertical-align: middle;
    display: table-cell;

}

jsは必要ありません...

于 2013-10-05T07:09:22.560 に答える
1

それでも javascript が必要な場合は、私の解決策です...このバインドを使用して、変更されるたびに高さを取得でき、css を管理するアルゴリズムを作成できるはずです。

JS:

$('#inner').bind('getheight', function() {
    $('#inner').height();
});
于 2013-10-05T07:17:38.643 に答える