2012-10-18 124 views
0

真的沒有辦法將沒有javascript的絕對/相對定位元素居中嗎?如果元素的寬度是可靠的,我知道這很容易。沒有CSS解決方案嗎?我不得不訴諸於JavaScript?居中響應絕對定位元素

<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> 

注意:邊界只是爲了讓人們更容易瞭解事物的佈局;彎曲的角落更好。

(來源:http://blog.themeforest.net/tutorials/vertical-centering-with-css/

+0

ps。有關IE兼容性的信息,請參閱鏈接 – JohnLBevan

+0

這是相當有創意的答案,表格。 –

+0

確實很聰明! –