2012-07-27 94 views
2

我試圖集中3個浮動DIV。如果我給父母DIV display:table;和孩子DIVs display:cell;然後它就像一張桌子一樣。有另一種方法嗎?中心浮動DIV

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="UTF-8" /> 
     <title>Center Div</title> 
     <style type="text/css"> 
     #container 
     {    
      text-align:center; 
      margin:0 auto;   
      display:table; 
     } 
     #container div 
     {   
      float:left; 
      padding:5px; 
      display:cell; 
     } 
     </style> 
    </head> 
    <body> 
     <div id="container"> 
      <div style="background-color:yellow">Text 1</div> 
      <div style="background-color:lightgreen">Text 2</div> 
      <div style="background-color:lightblue">Text 3</div>    
     </div> 
    </body> 
</html> 
+0

你會提供您想既然做形象也更好地理解想要的是什麼用戶圖像得到 – 2012-07-27 08:20:06

回答

-2

您需要分配寬度父div這樣的:

#container 
    {    
    text-align:center; 
    margin:0 auto; 
    width:150px;  
    } 

My Fiddle

+2

這不是真正的中心。它只適用於容器寬度是固定的。文本對齊:中心沒有做任何事情。 – dmzza 2013-03-06 04:38:22

+0

@dmzza當OP自己發現答案有幫助時,你爲什麼會哭泣? – 2013-03-07 16:23:49

+1

+1因爲它爲我想要的工作罰款! – 2013-06-12 16:17:14

0

我認爲,如果你定義的寬度,顯示:塊,邊緣0px auto的,位置:相對它應該工作。

-2

爲什麼你不想使用表的任何原因?

它可能會解決目的。表是不是因爲他們是做出來是所有邪惡;)

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="UTF-8" /> 
     <title>Center Div</title> 
     <style type="text/css"> 
     #container 
     {     
      text-align:center; 
      margin:0 auto; 
     } 
     #container td 
     { 
      padding:5px; 
     } 
     </style> 
    </head> 
    <body> 
     <div id="container"> 
      <table cellpadding="0" cellspacing="0" style="margin-left:auto;margin-right:auto;"> 
       <tr> 
        <td style="background-color:yellow">Text 1</td> 
        <td style="background-color:lightgreen">Text 2</td> 
        <td style="background-color:lightblue">Text 3</td> 
       </tr> 
      </table> 
     </div> 
    </body> 
</html> 
+1

是的,實際上他們是。根據W3你不應該使用表格來進行佈局,它是一種非語義的破解方式 - 看到這個規範是在2000年編寫的,並沒有被修改或改變,因爲:http:// www.w3.org/TR/WCAG10-TECHS/#tech-avoid-table-for-layout – 2013-04-17 15:30:27

+0

你現在真的不應該使用表格進行定位。表格有其目的,應該僅用於此目的:在表格中顯示東西。 – jipiboily 2013-10-15 19:15:37

0

試試這個,

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="UTF-8" /> 
     <title>Center Div</title> 
     <style type="text/css"> 
     #container 
     {    
      text-align:center; 
      margin:0 auto; 
      width:200px; 

     } 
     #container div 
     {   
      float:left; 
      padding:5px; 
      display:cell; 
     } 
     </style> 
    </head> 
    <body> 
     <div id="container"> 
       <div style="background-color:yellow">Text 1</div> 
       <div style="background-color:lightgreen">Text 2</div> 
       <div style="background-color:lightblue">Text 3</div> 

     </div> 
    </body> 
</html>