2012-04-19 63 views
1

我想實現是同時圍繞一個字符串迫使它的div容器的底部之間居中的差異,但下面產生在不同瀏覽器3分不同的結果。瀏覽器

<style> 
     #outer { 
      position: relative; 
      background-color:blue; 
      height: 50px; 
      text-align: center; 
     } 

     #inner { 
      bottom: 0px; 
      position: absolute; 
      background-color:red; 
     } 
     </style> 
    </head> 
    <body> 
     <div id="outer"> 
      <span id="inner"> 
       aaaaaaaaaaaaaaaaaaaaaaa 
      </span> 
     </div> 
    </body> 

Chrome將#inner完美中心。 的Firefox開始從完美的中心向右輸出字符串,所以不知它看起來有點移位,時間越長字符串,比較明顯的眼球。 IE開始從左邊輸出文本。

對此有什麼解決辦法?哪些行爲符合標準?

回答

1

嘿,我覺得你應該給左,右:0在你的CSS像這樣

#inner { 
    position: absolute; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    background-color: red; 
} 
+0

你有道理。 – 2012-04-19 12:56:40

0

text-align: center;對DIV#內,並從DIV#外將其刪除。

+0

不會有任何影響,因爲內心是一個內聯元素。 – Christoph 2012-04-19 11:46:22

+0

你是對的,對不起,我的錯! – sp00m 2012-04-19 11:49:26

0

你的內心應該有一個負邊距,就是你的元素寬度的1/2。

#inner{ 
    position:absolute; 
    left:50%; 
    width:500px; 
    margin-left:-250px; 
} 
0

定位與絕對定位組合垂直居中您的內部元件是唯一可能的,如果聲明在其上的寬度,這僅具有效果,如果它是一個非直列元件。

所以你需要這個額外的規則:

#inner{ 
    display:inline-block; 
    width:<yourWidth>px; 
    margin-left:-<yourWidth/2>px; 
    left:50%; 
} 

或者,你可以做到以下幾點:

#inner{ 
    display:block; 
    left:0; 
    text-align:center; 
} 

側面說明:根據規格0可能永遠不會有一個單位,所以總是寫top:0;而不是top:0px;

0

那麼,你可以使用jQuery,如果CSS是古怪的。首先使用CSS隱藏內容,然後讓jQuery將其集中並在內容加載時取消隱藏。像這樣的東西應該工作:

$(document).ready(function() { 
    var newWidth = ($('#outer').width() - $('#inner').width())/2; 
    $('#inner').css({'visibility': 'visible', 'margin-left': newWidth}); 
}); 

這是未經測試,但應適用於任何條件。