سؤال

I have the following css which in chrome and safari centers an absolutely positioned image

.productImg {
     width: 100%;
     position: absolute;
     left: 50%;
     margin-left: -50%;
}

However in internet explorer 7 this doesn't center the image. Instead the image stays on the left side of the container div. My question is, how can I make my script above work in ie7?

هل كانت مفيدة؟

المحلول

If your image is the width of its container and you want it centered, why not just align it to the left?

.productImg 
{
    width: 100%;
    position: absolute;
    left: 0;
}

نصائح أخرى

Have you tried margin: 0 auto; text-align: center;? This is the best way to center horizontally.

For this you should wrap a div something like this:

<div class="hCenter">
<div class="productImg"></div>
</div>

Then css would be as following:

.hCenter{
position: relative;
margin: 0 auto;
text-align: center;
}
productImg{
/*now you can align position absolute*/
/*other code in here*/
}

Edit

If you still want to be aligned horizontally centered with absolute position, you could do like this demo

.productImg {
     width: 50%;
     position: absolute;
     right: 25%; /* half of the width percentage*/
    background-color: red;
    height: 200px;
}

Edit 1

If your parent div is positioned absolutely, then you don't need to set position: absolute your .productImg. Just add margin: 0 auto; text-align: center;

You just need to center the parent div.

div {
    width: 300px /* give div a width */
    margin: 0 auto;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top