user2028856
user2028856

Reputation: 3193

CSS center position absolute image internet explorer

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?

Upvotes: 2

Views: 9533

Answers (3)

MikesBarto2002
MikesBarto2002

Reputation: 173

You just need to center the parent div.

div {
    width: 300px /* give div a width */
    margin: 0 auto;
}

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

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;

Upvotes: 1

Dom Ramirez
Dom Ramirez

Reputation: 2212

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

Upvotes: 2

Related Questions