2016-12-29 5 views
0

私は、水平に別の要素の中央に配置する必要がある要素を持っています。中心要素のCSSは、(私はuneccesaryコードを削除した)そうです:別の要素を基準にした要素の中心合わせ

#center-element{ 
    display: flex; 
    flex-direction: column; 
    align-items: stretch; 
    position: absolute; 
} 

私はバニラのJSを使用して、そうしなければなりません。私は試しました:

var targetPos = target.getBoundingClientRect(); 
centerDiv.style.top = (targetPos.top + targetPos.height) + "px"; 
centerDiv.style.left = (targetPos.left + (targetPos.width/2)) + "px"; 

しかし、それはオフです。何か案は?

JSFiddle

+0

...なぜちょうど両方のdiv要素に同じスタイルを与えていませんか?あなたが必要とするのは、幅:75%、テキストアライメント:両方の中心です。 –

+0

はい、私のコード(ここではありません)ではテキストではありません。 – MasterBob

+0

誤解を招くような例では役立たないが、display:inline-blockとmargin:0 auto;を試すことができます。あなたが中心に置いてくれる画像または要素の上に –

答えて

1

//Somehow center the div here 
 
var target = document.getElementById("target"); 
 
var centerDiv = document.getElementById("centerDiv"); 
 
var targetPos = target.getBoundingClientRect(); 
 
centerDiv.style.top = targetPos.bottom + "px"; 
 
centerDiv.style.left = targetPos.left + (target.offsetWidth - centerDiv.offsetWidth)/2 + "px";
#target { 
 
    background-color: lightblue; 
 
    text-align: center; 
 
    width: 75%; 
 
} 
 
#centerDiv { 
 
    display: flex; 
 
    flex-direction: column; 
 
    align-items: stretch; 
 
    position: absolute; 
 
}
<div id="target"> 
 
    This is the div 
 
</div> 
 
<div id="centerDiv"> 
 
    This is supposed to be horizontally centered <em>to the div element above</em> 
 
</div>

0

あなたはフレキシボックスを使用してそれを行うことができます。両方のdivをコンテナdiv内にラップし、そのコンテナにdisplay:flex;を適用することができます。

#target { 
 
    background-color: lightblue; 
 
    text-align: center; 
 
    width: 100%; 
 
} 
 
#centerDiv { 
 
    /* display: flex; 
 
    flex-direction: column; 
 
    align-items: stretch; 
 
    position: absolute; */ 
 
    text-align:center; 
 
} 
 
.container{ 
 
    display:flex; 
 
    width:75%; 
 
    flex-direction:column; 
 
    align-items:center; 
 
    justify-content:center; 
 
}
<div class="container"><div id="target"> 
 
    This is the div 
 
</div> 
 
<div id="centerDiv"> 
 
    This is supposed to be horizontally centered <em><br/>to the div element above</em> 
 
</div> 
 
</div>

+0

フレックスボックスがフレックスボックス内にあるとどうなりますか? – MasterBob

+0

あなたはそれを使用することができます。それはレイアウトを壊すことはありません。 – ab29007

+0

しかし、ほとんどの場合、テキストは 'text-align:center;'で、divは 'margin:0 auto;'で区切ることができます。 – ab29007

関連する問題