2013-11-27 21 views
-1

HTML如何垂直對準在中心在div不管屏幕尺寸的

<div id="centered"> 
//Some Content 
</div> 

CSS

#centered 
{ 
margin-left:auto; 
margin-right:auto; 
} 

上面的代碼被水平地對準,而不管屏幕尺寸。 如何在中心垂直對齊相同的div?

+0

看ATH這一塊,http://stackoverflow.com/questions/18276572/how-to-center-a-div-tag-in-a-html-page-without-being - 受縮放影響 –

回答

0

,如果你知道DIV

的寬度和高度,然後(我假定它的400×200),所以只給否定這些尺寸保證金一半財產價值。你的內容將集中

#centered{ 
    position:absolute; 
    top:50%; 
    left:50%; 
    margin-left:-200px; 
    margin-top:-100px; 
    } 

在情況下,如果你的寬度和高度動態的,然後put this div in table,讓您可以垂直和水平這對準中間

0

嘗試下面的CSS:

Demo

#centered 
{ 
    position: absolute; 
    height: auto; 
    width: auto;  
    left: 50%; 
    top: 50%; 
    transform: translate(-50%, -50%);  
    -webkit-transform: translate(-50%, -50%); 
    -moz-transform: translate(-50%, -50%); 
    -ms-transform: translate(-50%, -50%); 
} 
0

試試看這個代碼..

#centered 
{ 
    margin-left:auto; 
    margin-right:auto; 
    display: table-cell; // here is the trick 
    vertical-align:middle; // and this 
    height:200px; 
    border:1px solid blue; 
} 

http://jsfiddle.net/c5Y27/

+0

謝謝。如果我的內容是這樣的:http://jsfiddle.net/c5Y27/3/ – Billy

+0

可能是這個.. http://jsfiddle.net/c5Y27/5/ – zzlalani