2013-06-12 82 views
0


我所要做的應該是這樣的:
horizontally/vertically aligned inner divs
...但我inner_top DIV(與紅色背景)是水平居中,結束了這樣看:
all jacked up!

衝突似乎使用display: inline-block'inner_top股利,這似乎使垂直爲中心雖然,除了兩個div之間的奇怪間距。
我怎麼能水平和垂直居中另一個div內的兩個div?


這裏是我的代碼:

<!DOCTYPE html> 
<html> 
    <head> 
     <title> 
      CSS sucks!!! 
     </title> 

     <style type = "text/css"> 

      #outer { 
       width: 250px; 
       height: 500px; 
       border: 5px solid black; 

       /* for vertically-centering inner divs: */ 
       display: table-cell; 
       vertical-align: middle; 
      } 
        #inner_top { 
         width: 75px; 
         height: 175px; 
         background-color: red; 

         /* horizontally-centered: */ 
         margin: 0 auto; 

         /* vertically-center both this and the bottom div: 
         (but now horizontal-alignment doesn't work on this div!) */ 
         display: inline-block; 

        } 
        #inner_bottom { 
         width: 150px; 
         height: 150px; 
         background-color: blue; 

         /* horizontally-centered: */ 
         margin: 0 auto; 
        } 
     </style> 
    </head> 
    <body> 
     <div id = "outer"> 

      <div id = "inner_top"> 
      </div> <!-- end of inner top --> 

      <div id = "inner_bottom"> 
      </div> <!-- end of inner_bottom --> 
     </div> <!-- end of outer div --> 
    </body> 
</html> 
+2

當我刪除'display:inline-block'時,該示例適用於我... –

+0

以上爲+1。 http://jsfiddle.net/JSWorld/MhbmY/ –

+0

哈哈,太棒了!我不敢相信我沒有嘗試過......呃,我覺得自己像個假人。 @MrLister - 如果您以此作爲答案,我會接受。 –

回答

2

我把你的代碼中的jsfiddle的這個簡單的塊,和它的作品的時候,當我從上面div的風格除去display:inline-block
http://jsfiddle.net/MrLister/5ZHdK/

/*display: inline-block;*/ 

仍然不知道從哪裏你說的「垂直中心這兩者和底格」來源於雖然;聽起來你不能在沒有內聯塊的情況下工作嗎?

+0

謝謝@MrLister。在測試了幾個不同的東西后,我得到了垂直和水平對齊的困惑,在兩個內部div上設置'display:inline-block;'將它們彼此對齊... –

0

您需要使用margin:0 auto你試圖中心的所有子元素。

margin:0 auto的孩子不能是塊類型。

http://jsfiddle.net/EDpgS/

+0

'margin:0 auto'出現在兩個子元素中,但正如你所說的那樣:display:inline-block;是問題所在。 –

+1

邊距對內聯元素根本無效。內聯元素通過'text-align:center'居中。 – cimmanon

1

只是他們居中使用CSS

#inner_top { 
    margin-left: auto; 
    margin-right: auto; 
} 
#inner_bottom { 
    margin-left: auto; 
    margin-right: auto; 
} 
+0

'margin:0 auto'已經出現在'inner_top'和'inerr_bottom' CSS中,這相當於這個。 –

相關問題