2013-10-09 51 views
0

如何始終居中對齊水平和垂直容器,無論內容如何?以下是我想要做的一個基本例子。無論內容如何,​​始終將容器居中對齊水平和垂直

此方法是否正確,或者有更簡單的方法解決我的問題?

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
     <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
     <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
     <title>3 columns</title> 


     <style> 
     div.container { 
      height: 200px; 
      width: 100%; 
      margin-left: auto; 
      margin-right: auto; 
      margin-top: 25%; 
      margin-bottom: 20%; 
     } 

     div.col { 
      float: left; 
      width: 25%; 

     } 
     </style> 

     </head> 
     <body> 

     <div class="container"> 
      <div class="col" align="center">This is col 1</div> 
      <div class="col" align="center">This is col 2</div> 
      <div class="col" align="center">This is col3</div> 
     </div> 


     </body> 
     </html> 

回答

1
.container { 
    position: absolute; 
    left: 50%; 
    top: 50%; 

    /* 
    Nope =(
    margin-left: -25%; 
    margin-top: -25%; 
    */ 

    /* 
    Yep! 
    */ 
    -webkit-transform: translate(-50%, -50%); 
    -ms-transform: translate(-50%, -50%); 
    transform: translate(-50%, -50%); 

    /* 
    Not even necessary really. 
    e.g. Height could be left out! 
    */ 
    width: 40%; 
    height: 50%; 
} 

來源:http://css-tricks.com/centering-percentage-widthheight-elements/

注意,transform屬性將需要一些瀏覽器前綴,在寫這篇文章(-ms-webkit)的時間。 http://caniuse.com/transforms2d

+1

請記住在適當的前綴WebKit瀏覽器(HTTP:/ /caniuse.com/transforms2d)。 –

+0

當您離開您的評論時正在處理該過程。 ;) – Benjam

+0

如果IE8和更低版本需要支持,我會選擇[table CSS或僞影](http://css-tricks.com/centering-in-the-unknown/)方法。此外,如果元素更高,這些元素不存在將元素推出視口頂部的問題。 –

0

爲尼爾斯Keurentjes說... table-cell是不錯fiddle

HTML:

<div class="outer"> 
    <span class="inner"> 
     <img src="http://www.google.co.in/trends/resources/2327917647-google-icon.png"/> 
    </span> 
</div> 
<div class="outer"> 
    <span class="inner"> 
     <span class="innerinner">blah blah blah blah blah blah blah blah blah blah</span> 
    </span> 
</div> 

CSS:

.outer{ 
    width:300px; 
    height:200px; 
    border:1px solid blue; 
    display:table; 
    text-align:center; 
} 

.inner{ 
    display:table-cell; 
    vertical-align:middle; 
    border:1px solid red; 
} 
.inner img{ 
    border:1px solid orange; 
} 
.innerinner{ 
    border:1px solid red; 
} 
+0

這不是把一列放在另一個之上嗎?我之後是3頁水平欄,將在頁面中居中。 – user2496011

相關問題