2016-12-29 8 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

오해의 소지가있는 예제를 돕기는 어렵지 만 다음과 같이 표시 할 수 있습니다. inline-block and 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

당신은 인 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

플렉스 박스가 플렉스 박스 내부에있을 때 어떻게됩니까? – MasterBob

+0

을 사용할 수 있습니다. 그것은 레이아웃을 깨지 않습니다. – ab29007

+0

하지만 대부분 텍스트를'text-align : center;'로 정렬하고'margin : 0 auto; '로 div로 만들 수 있습니다. – ab29007