Search code examples
htmlcsscross-browserpositioncenter

centering image in div


I have a square <div> (70px x 70px) which will contain an image of a variable dimensions(Square, landscape or potrait). I want this image to be symmetrically centered inside the <div>. how do I get it..?

<div class="img-polaroid" style="width: 70px; height: 70px; background-color: black; text-align:center;">
    <image src='.base_url("images/store/images/".$image->image).'  />
</div>

The actual size of the image can be greater than 70px x 70px. But it should fit symmetrically in the center.

I also have to make it cross-browser compatible.. Help Appreciated...


Solution

  • Must it be an <img> element?

    You can set the image as background of the <div> with background-position:center center - this is very easy to do, not using javascript and cross-browser..

    Use it like this:

    <div class="img-polaroid" style="width: 70px; height: 70px; background:url('.base_url("images/store/images/".$image->image).') center center no-repeat black; text-align:center;"></div>
    

    Check this Working jsFiddle. In terms of browser support I've never come across a browser that doesn't support this.

    It is sure to work on:

    • Netscape 6+
    • Mozilla 1+
    • Firefox 1+
    • Internet Explorer 4+
    • Opera 3+
    • Safari 1+