2011-11-21 36 views
5

更新提供了佈局的上下文如何將IE7中絕對定位的div居中?

我的頁面結構比較簡單。該頁面由兩個div組成,絕對定位。一個以另一個爲中心。 enter image description here

<div id="protocol_index_body_wrapper"> 
    <div id="protocol_index_body"> 
    </div> 
</div> 

其中有相應的CSS:

#protocol_index_body_wrapper { 
    background: url("/images/stripe.png") repeat scroll 0 0 transparent; 
    position: absolute; 
    top: 120px; 
    left: 0px; 
    right: 0px; 
    bottom: 10px; 
} 
#protocol_index_body { 
    width: 960px; 
    margin: 0 auto; 
    position: absolute; 
    top: 0; 
    left: 0; 
    right: 0; 
    bottom: 0; 

} 

預期的行爲被認爲是在圖像的上方。此行爲出現在IE8,Firefox和Chrome中。但是,在IE7中,應該居中的div與左側齊平。有任何想法嗎?

+0

嘗試增加'文本對齊:中心;''到#protocol_index_body' –

+0

都能跟得上沒有有效果。 –

+0

嘗試在body_wrapper div上設置100%的寬度。 –

回答

-1

text-align:center到包裝,或<div align=center>(醜陋的,我知道,但作品)

或JS:只對IE6 +

document.getElementById("protocol_index_body_wrapper").style.marginRight = (document.body.clientWidth - 50)/2_+"px" 

作品。

+0

我相信這是一個IE6錯誤的修復... –

4

試試這個:

#protocol_index_body { 
    width: 50px; 
    margin: 0 auto 0 -25px; 
    position: absolute; 
    top: 0; 
    left: 50%; 
    right: 0; 
    bottom: 0; 
    background-color: red; 
} 

或者......

#protocol_index_body { 
    width: 50px; 
    margin: 0 auto 0 50%; 
    position: absolute; 
    top: 0; 
    left: -25px; 
    right: 0; 
    bottom: 0; 
    background-color: red; 
} 
+0

工程,但只是因爲你使用了固定的邊距。無論其大小如何,都需要留在屏幕中央。 –

0

除非你需要家長的div有一個液體寬度(當你設定孩子這將是一個有點傻div的寬度),爲什麼不只是設置父div的寬度並添加margin:0 auto

+0

父div是子div上的全寬背景。 –

0

好,我發揮它周圍,這個作品相同的FF,Opera和IE 7:

#protocol_index_body_wrapper { 
    background-color:black; 
    padding: 0 0 20px 0; 
    position: absolute; 
    top: 120px; 
    left: 0px; 
    right: 0px; 
    bottom: 10px; 
    text-align: center; 
    width: 100%; 
    height: 100%; 
} 
#protocol_index_body { 
    width: 50px; 
    margin: 0 auto; 
    background-color: red; 
    height: 100%; 
} 
+0

正在設置屏幕布局的高度和寬度。查看更新的原始帖子。 –

0
autoCenterAlign = function() { 

    var bodyWidth = $("body").innerWidth(); 
    var protocolWidth = $("#protocol_index_body").innerWidth(); 
    if(protocolWidth < bodyWidth) { 

     $("#protocol_index_body").css("left",((bodyWidth-protocolWidth)/2)+"px"); 

    } 

} 

window.onload = autoCenterAlign; 
window.onresize = autoCenterAlign; 
jQuery(window).load(function() { 

    autoCenterAlign() 

});