How to center an absolutely positioned div within

2019-06-21 04:42发布

问题:

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.

<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?

回答1:

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;
}


回答2:

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?



回答3:

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:

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()

});


回答5:

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+.