2012-10-18 2 views
0

절대적으로/비교적 위치가 정해진 요소를 자바 스크립트없이 가운데에 배치 할 수있는 방법이 있습니까? 요소의 너비가 신뢰할 수 있다면 쉽다는 것을 안다. CSS 솔루션이 있습니까? 내가 자바 스크립트에 의지해야만 할까?반응이있는 절대적으로 배치 된 요소의 중심을 지정하십시오.

<body><div class="parent"><div class="child">This stuff changes</div></div></body> 

.child{margin:auto;position:absolute;left:50%} // this will center the left edge 
.parent{width:800px;height:430px;margin:auto;overflow:hidden;} 

답변

4

방법에 대해 :

.child { 
    margin-left: auto; 
    margin-right: auto; 
    display: table; 
} 

전체 데모 HTML :

<html> 
<head> 
    <style type="text/css" media="screen"> 
    .child { 
     margin-left: auto; 
     margin-right: auto; 
     display: table; 
    } 
    </style> 
</head> 
<body> 
    <!-- middle marker to test alignment --> 
    <table width="100%"><tr><td align="center" width="100%">|</td></tr></table> 
    <!-- actual thing we're trying to center --> 
    <div class="parent"> 
     <div class="child">123456789|987654321</div> 
    </div> 
</body> 

(출처 : http://solstice.co.il/blog/2008-02-26/horizontally-centering-content-dynamic-width-css)

또한 수직 중심의 경우 :

<html> 
<head> 
    <style type="text/css" media="screen"> 
    .parent { 
     width:800px; 
     height:430px; 
     margin:auto; 
     overflow:hidden; 
     border:2px solid cyan; 
     border-radius:25px; 
     -moz-border-radius:25px; /* Firefox 3.6 and earlier */ 
    } 
    .evilStepMother { /* i.e. comes between the parent and child */ 
     display: table-cell; 
     vertical-align: middle; 
     width: 800px; /* i.e. matches parent */ 
     height: 430px; /* i.e. matches parent */ 
     border:2px solid green; 
     border-radius:25px; 
     -moz-border-radius:25px; /* Firefox 3.6 and earlier */ 
    } 
    .child { 
     margin: auto; 
     display: table; 
     border:2px solid red; 
     border-radius:25px; 
     -moz-border-radius:25px; /* Firefox 3.6 and earlier */ 
    } 
    </style> 
</head> 
<body> 
    <!-- middle marker to test alignment --> 
    <table width="100%"><tr><td align="center" width="100%">|</td></tr></table> 
    <!-- actual thing we're trying to center --> 
    <div class="parent"><div class="evilStepMother"> 
     <div class="child">123456789|987654321</div> 
    </div></div> 
</body> 

주의 : 경계선은 물건 배치 방법을보다 쉽게 ​​볼 수 있도록 해줍니다. curvy 모서리는 단지 더 멋지다.

(출처 : http://blog.themeforest.net/tutorials/vertical-centering-with-css/)

+0

ps. IE 호환성에 대한 정보는 링크를 참조하십시오. – JohnLBevan

+0

꽤 창의적인 대답 인 표입니다. –

+0

참으로 영리한! –

관련 문제