2

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?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
user2028856
  • 3,063
  • 8
  • 44
  • 71
  • Ah, the reminiscing sound of "how can I make this work in IE7." Not a definite duplicate, but maybe http://stackoverflow.com/questions/6/why-doesnt-the-percentage-width-child-in-absolutely-positioned-parent-work-in-i?rq=1 can help. – jeremy Aug 14 '13 at 02:23
  • The problem is that I already have a fixed height/width for the parent div and the problem still persists. The answer to the other thread was that the parent div had no fixed height/width – user2028856 Aug 14 '13 at 02:34

3 Answers3

2

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;
}
Dom Ramirez
  • 2,132
  • 2
  • 23
  • 29
  • Cool. I wish I had the time to figure out why IE7 interpreted your css differently, but it might not be such a big deal given IE7's plummeted market share: http://theie7countdown.com/ – Dom Ramirez Aug 14 '13 at 04:24
1

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;

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

You just need to center the parent div.

div {
    width: 300px /* give div a width */
    margin: 0 auto;
}
MikesBarto2002
  • 181
  • 3
  • 15