How to vertically center an image inside of a div element in HTML using CSS?

I have a markup like this:

<div>
  <img />
</div>

The div is higher than img:

div {
  height: 100px;
}

img {
  height: dynamic-value-smaller-than-100px;
}

I need the image to be in the middle of the div (have same amout of white space above and below it).

I tried this and it does not work:

div {
  vertical-align: middle;
}

if your image is purely decorative, then it might be a more semantic solution to use it as a background-image. You can then specify the position of the background

background-position: center center;

If it is not decorative and constitutes valuable information then the img tag is justified. What you need to do in such case is style the containing div with the following properties:

div{
    display: table-cell; vertical-align: middle 
}

Read more about this technique here. Reported to not work on IE6/7 (works on IE8).


Another way is to set your line-height in the container div, and align your image to that using vertical-align: middle.

html:

<div class="container"><img></div>

css:

.container {
  width: 200px; /* or whatever you want */
  height: 200px; /* or whatever you want */
  line-height: 200px; /* or whatever you want, should match height */
  text-align: center;
}

.container > img {
  vertical-align: middle;
}

It's off the top of my head. But I've used this before - it should do the trick. Works for older browsers as well.


Let's say you want to put the image (40px X 40px) on the center (horizontal and vertical) of the div class="box". So you have the following html:

<div class="box"><img /></div>

What you have to do is apply the CSS:

.box img {
    position: absolute;
    top: 50%;
    margin-top: -20px;
    left: 50%;
    margin-left: -20px;
}

Your div can even change it's size, the image will always be on the center of it.