EGHDK
EGHDK

Reputation: 18120

Center an image

I have an image that is 500px wide. It is inside of a div. The width of the div is 250px. How can I align the image centered inside of the div? Should I use top or left or should I have negative margins?

Upvotes: 0

Views: 126

Answers (4)

Manish Sharma
Manish Sharma

Reputation: 1720

try this one (not sure about ie-6 but work fine in ie-7 and plus)

<style>
.test{ height:250px; width:250px; overflow:hidden; position:relative;}
.test img{ position:absolute; top:50%; left:50%; margin-left:-250px; margin-top:-250px; height:500px; width:500px;}
</style>

<body>
<div class="test"><img src="img.png" alt="img" /></div>
</body>

if is it possible to use that image as background you can try this one

.test{height:250px; width:250px; background:url(img-path.png) no-repeat 50% 50%;}

Upvotes: 0

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32162

Demo

Hey now used to display table-cell properties as like this

<div class="parent">
<img src="http://www.gravatar.com/avatar/3c6597370b476903ed475f70b4b3ce31?s=32&d=identicon&r=PG">
</div>

Css

.parent{
border:solid 1px red;
  display:table-cell;
  width:300px;
  height:300px;
  vertical-align:middle;
  text-align:center;
}
.parent img{
vertical-align:top;
}

Demo

Upvotes: 0

Kjartan
Kjartan

Reputation: 19081

Can you change (or at least add) something in the html around the image? This is kind of an old trick, and is a little awkward in that it requires you to add an extra <div> around the image, but it works quite nicely if you're ok with that (Note, added some borders to make the effect easily visible while testing):

<div style="width:250px; border: solid 2px red;">
    <!-- Place the following div at 50%: -->
    <div style="width: 500px; margin-left:50%; border: solid 2px blue;">
        <!-- ...then move the image back by half of it's own width: -->
        <img style="width:500px; margin-left:-250px; border: solid 3px green;" />
    </div>
</div>

Upvotes: 0

thirdender
thirdender

Reputation: 3951

I would use negative margins: #myDiv img { margin: 0 -125px; }. This only works if you know the width of both the DIV and the IMG though.

Upvotes: 3

Related Questions