How to center an absolutely positioned div within

2019-06-21 05:08发布

UPDATED PROVIDING CONTEXT FOR THE LAYOUT

I have a relatively simple structure for my page. The page is composed of two div's both absolutely positioned. One is centered within the other.enter image description here

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

Which has the corresponding 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;

}

The expected behavior is seen in the image above. This behavior is present in IE8, Firefox, and Chrome. However, in IE7 the div which should be centered is flush against the left side. Any ideas?

5条回答
劳资没心,怎么记你
2楼-- · 2019-06-21 05:16

Try this:

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

Or ...

#protocol_index_body {
    width: 50px;
    margin: 0 auto 0 50%;
    position: absolute;
    top: 0;
    left: -25px;
    right: 0;
    bottom: 0;
    background-color: red;
}
查看更多
闹够了就滚
3楼-- · 2019-06-21 05:29

Okay I played around with it and this works identical in FF, Opera and IE7:

#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%;
}
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-06-21 05:36

Unless you need the parent div to have a fluid width (which would be a little silly when you're setting the child div's width), why not just set the parent div's width and add margin:0 auto?

查看更多
唯我独甜
5楼-- · 2019-06-21 05:40
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()

});
查看更多
Animai°情兽
6楼-- · 2019-06-21 05:40

text-align:center to the wrapper, or <div align=center> (ugly, I know, but works)

or with JS:

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

works only on IE6+.

查看更多
登录 后发表回答