2013-06-18 3 views
2

자바 스크립트로 div를 세로로 가운데에 놓으려고합니다. 텍스트가 바뀌기 때문에 고정 된 높이를 사용할 수 없습니다.자바 스크립트로 세로 중심 div (가변 높이)

Jquery없이이 작업을 수행하고 싶습니다.

#box2 { 

    width: 100%; 
    height: 100%; 
    position:relative; 
    background-color: orange; 

} 
      #informationBox { 

      padding: 0.5em; 
      background-color: #fff; 
      border-radius: 12pt; 
      border: solid black 3pt; 
      max-width: 683px; 
      margin: 0 auto; 
      text-align: center; 
     } 

자바 스크립트 :

var container = document.getElementById("#box2"); 
var inner = document.getElementById("#informationBox"); 
var inHeight = inner.offsetHeight; 

container.style.height=(window.innerHeight); 
container.style.width=window.innerWidth; 

var conHeight=container.offsetHeight; 

inner.style.marginTop=((conHeight-inHeight)/2); 

어떤 도움이 될 것이다 당신은 거의 그것을 가지고, 당신은 단지 몇 가지를 변경해야합니다 :)

http://jsfiddle.net/tmyie/EttZQ/

답변

4

좋아요. 첫째, getElementById은 선택기가 아닌 id 문자열을 사용합니다. 둘째, 'px'를 스타일 선언에 추가해야합니다. 정적이 아닌 다른 http://jsfiddle.net/EttZQ/1/

+0

실제 사이트에서 컨테이너는 상대적으로 설정됩니다. 이렇게하면 jsfiddle에서 코드가 분리됩니다. 컨테이너가 상대적인 경우 솔루션이 있습니까? –

0

만들기 컨테이너 POS 아무것도 :

var container = document.getElementById("box2"); 
var inner = document.getElementById("informationBox"); 
var inHeight = inner.offsetHeight; 
container.style.height = window.innerHeight; 
container.style.width = window.innerWidth; 
var conHeight = container.offsetHeight; 

inner.style.marginTop = ((conHeight-inHeight)/2)+'px'; 

여기에 업데이트 된 바이올린입니다. 상자 : 절대 절대 값. 상단 : 50 % 상자 높이가 변경되면 상자 상단 여백을 -1 ​​* 높이/2로 설정합니다.

2

하나의 간단한 CSS 솔루션.

당신은 당신의 요소의 너비/높이를 계산하고 당신이 그것을 중앙에 원하는 영역 50 %를 변경해야

body { 
    margin: 0; 
} 
#box2 { 
    width: 100%; 
    height: 100%; 
    position:absolute; 
    background-color: orange; 
} 
#informationBox { 
    padding: 0.5em; 
    background-color: #fff; 
    border-radius: 12pt; 
    border: solid black 3pt; 
    max-width: 100px; 
    margin: 0 auto; 
    text-align: center; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
} 

http://jsfiddle.net/antouank/EttZQ/2/.

4

줄 높이 속성과 함께 js를 사용합니다.

자바 스크립트가 적고 정확한 센터링.

상자/정보는

또한 창 크기를 조절 최소/최대 너비/높이를 & % 또는 픽셀을 ... 할 수 있습니다.

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>center</title> 
<style> 
html,body{ 
width:100%; 
height:100%; 
margin:0; 
padding:0; 
} 
#box{ 
width:100%; 
height:100%; 
text-align:center; 
} 
#info{ 
display:inline-block; 
margin:0;padding:0 16px; 
line-height:24px; 
border-radius: 12pt; 
border: solid black 3pt; 
text-align: center; 
vertical-align:middle; 
box-sizing: border-box; 
} 
</style> 
<script> 
var center=function(){ 
var b=document.getElementById('box'); 
b.style['line-height']=b.offsetHeight+'px'; 
} 
window.onload=center; 
window.onresize=center; 
</script> 
</head> 
<body> 
<div id="box"><div id="info">center me pls<br>test</div></div> 
</body> 
</html>