Center an Image vertically and horizontally using CSS

How do I vertically and horizontally center an image when I do not know the size of it? I asked this question and someone suggested using a table. This isn't the first time I heard a table can do it but I tried without luck.

Searching SO only got me results when I do know the size of the image. How do I do this with a table?

NOTE: JavaScript/jQuery is not preferred but if there's a solution with it I'm open to it.


Solution 1:

Pretty easy, this is the format of all my images/containers:

<div class="photo"><img /></div>
<style type="text/css">
  div.photo { height: 100px; line-height: 100px;text-align:center; }
  div.photo img { vertical-align:middle;}
</style>

Solution 2:

The CSS Method

You can set an explicit height and line-height on your container to center an image:

<div id="container">
    <img src="http://placekitten.com/200/200" />
</div>

<style>
    #container { height: 600px; line-height: 600px; text-align: center }
    #container img { vertical-align: middle }
</style>

See it in action: http://jsfiddle.net/jonathansampson/qN3nm/

The HTML/Table Method

The table method follows. It's merely utilizing the valign (vertical-align) property:

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <img src="someHeight.jpg" />
      </td>
    </tr>
  </tbody>
</table>

A jQuery Plugin

Since you tagged this question "jQuery," I'll provide a reference to the jQuery Center Plugin that also achieves vertical/horizontal centering by using CSS positioning and dynamic reading of an elements dimensions: http://plugins.jquery.com/project/elementcenter

Solution 3:

With a table:

<table height="400">
    <tbody>
        <tr>
            <td valign="middle"><img /></td>
        </tr>
    </tbody>
</table>

The 400 is just something I picked. You will need to define a height on table so it is taller than your image.

A jquery solution would be good if you wanted to try and use divs and junk, but if you don't care you don't care. You also have to rely on JS being turned on.

HTML:

<div id="imgContainer" style="position:relative;">
    <img style="position:absolute;" />
</div>

JS:

$('#imgContainer > img').each(function(){
    //get img dimensions
    var h = $(this).height();
    var w = $(this).width();

    //get div dimensions
    var div_h =$('#imgContainer').height();
    var div_w =$('#imgContainer').width();

    //set img position
    this.style.top = Math.round((div_h - h) / 2) + 'px';
    this.style.left = '50%';
    this.style.marginLeft = Math.round(w/2) + 'px';
});