How to make an image center (vertically & horizontally) inside a bigger div [duplicate]

Solution 1:

Working in old browsers (IE >= 8)

Absolute position in combination with automatic margin permits to center an element horizontally and vertically. The element position could be based on a parent element position using relative positioning. View Result

img {
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

Solution 2:

Personally, I'd place it as the background image within the div, the CSS for that being:

#demo {
    background: url(bg_apple_little.gif) no-repeat center center;
    height: 200px;
    width: 200px;
}

(Assumes a div with id="demo" as you are already specifying height and width adding a background shouldn't be an issue)

Let the browser take the strain.

Solution 3:

another way is to create a table with valign, of course. This would work regardless of you knowing the div's height or not.

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

but you should always stick to just css whenever possible.

Solution 4:

I would set your larger div with position:relative; then for your image do this:

img.classname{
   position:absolute;
   top:50%;
   left:50%;
   margin-top:-25px;
   margin-left:-25px;
}

This only works because you know the dimensions of both the image and the containing div. This will also let you have other items within the containing div... where solutions like using line-height will not.

EDIT: Note... your margins are negative half of the size of the image.

Solution 5:

This works correctly:

display: block;
margin-left: auto;
margin-right: auto 

else try this if the above only gives you horizontal centering:

.outerContainer {
   position: relative;
}

.innerContainer {
   width: 50px; //your image/element width here
   height: 50px; //your image/element height here
   overflow: auto;
   margin: auto;
   position: absolute;
   top: 0; left: 0; bottom: 0; right: 0;
}