2013-01-01 43 views
0

我正在垂直和水平居中放置一個元素。一切工作正常,除了一個問題:我可以在IE7垂直中心img,但我不能集中div。什麼風格IE適用於圖像,不適用於div?可以在IE7中居中但不能居中div

HTML

<!-- image - works correctly --> 
<div class="container"> 
    <img class="inner" src="http://placekitten.com/200/200?image=2" /> 
</div> 
<br/> 
<!-- div - doesn't work (aligned to top) --> 
<div class="container"> 
    <div class="inner">123</div> 
</div> 

CSS:

.container { 
    height: 300px; 

    background: #EEE; 
    text-align: center; 
    line-height: 300px; 
} 

.inner { vertical-align: middle; width: 100px; 
height: 100px; background:red; display: inline-block; line-height: 1.3; }​ 

小提琴:

http://jsfiddle.net/kpdxu/7/

另外:

  • 我不知道的DIV
  • 我可以使用JavaScript大小,但因爲它含有動態內容

謝謝你,我不能得到DIV的大小!

+0

在IE7,'直列block'僅支持那些自然聯元素,因此,不上的DIV。您可以使用'margin:auto'將塊元素(如DIV)居中。 –

+0

我可能讀錯了,但我認爲他們正在尋找一種垂直對齊div的方法。 – gotohales

+0

@ŠimeVidas謝謝,完全忘了這一點。 – Marvin3

回答

1

使用本css

.container { 
    height: 300px; 
    background: #EEE; 
    text-align: center; 
    line-height: 300px; 
    position:relative; //<--this will hold the absolute positioned elements 
} 

.inner { 
    vertical-align: middle; 
    width: auto; 
    height: auto; 
    background:red; 
    display: block; // <--display block will do for ie 7 
} 
通過jQuery

$.fn.center = function() { 
    this.css("position","absolute"); 
    this.css("top", ($('.container').height() - this.height())/2 + "px"); 
    this.css("left", ($('.container').width() - this.width())/2 + "px"); 
    return this; 
} 

然後使用它像這樣

$('.inner').each(function(){ 
    $(this).center(); 
}); 

但父母必須是position relative

結帳小提琴:http://jsfiddle.net/kpdxu/14/

+0

你對代碼做了什麼改變? –

+0

剛剛更新了答案和評論。 – Jai

+0

@JA不幸的是,它不是一個選項,因爲元素的大小是動態的,可以是任何東西。 – Marvin3