2016-12-29 82 views
0

我有一個元素應該水平居中到另一個元素。居中元素的CSS是這樣的(我刪除了不相關的代碼):相對於另一個元素居中元素

#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

很難幫助一個誤導性的例子,但你可以嘗試顯示:內聯塊和邊距:0自動;在你想要的圖像或元素中心 –

回答

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

可以使用Flexbox的做到這一點。您可以將兩個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

當Flexbox在Flexbox內時會發生什麼? – MasterBob

+0

你可以使用它。它不會破壞佈局。 – ab29007

+0

,但你可以主要使用'text-align:center;'和div與'margin:0 auto; – ab29007

相關問題