How To Vertically Center an Image in a DIV (All Browsers)

Horizontally centering in CSS has always been fairly trivial, but vertical centering is another story. So here are two methods guaranteed to work across all browsers (including IE6) for vertically centering an image.

container-img

Method 1: The Line Height Method

This method involves setting the line-height property in css, to be the same as the containers height. It works because an image is only considered to be one line, and by setting the image’s vertical align property, we can make it sit in the middle of the line.

line-height

Requirements:

  • A fixed height container (e.g. 200px)
  • Any size image
  • A container taller than the image

Browsers:

All browsers (IE6+)

The Code

<div id="container">
    <img src="myimage.jpg" alt="image" />
</div>
#container {
    height: 200px;
    line-height: 200px;
}

#container img {
    vertical-align: middle;
}

 Method 2: The Absolute Position + Negative Margins Method

The negative margins method is slightly trickier in terms of how it works, but the code is still super simple. Negative margins might seem like a hack, but they are perfectly valid CSS, in fact the W3C even say “Negative values for margin properties are allowed”. Negative margins work in 2 ways, when you apply a negative margin to the top/left margins of an element, it moves the element in that direction; applying them to the right/bottom margins pulls the subsequent elements towards the element. Seems tricky, but in practice its pretty simple. In this example, we are going to using an image thats 200px in height.

negative-margins-1

 

negative-margins-2

 

negative-margins-3Requirements

  • Any size container
  • Fixed height image

Browsers

All browsers (IE6+)

Code

<div id="container">
    <img src="myimage.jpg" alt="image" />
</div>
#container {
    width:960px;
    height:600px;
    position:relative; /* Set as position relative to the IMG will move relative to this container */
}

#container img {
    position:absolute;
    top:50%; /* Move the image down, so its top is half way down the container */
    margin-top:-100px; /* Move the image back up half its height */
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*