How to center vertically img in a div

Hi everybody,

please can you help me?
I have this code, with a div box with given height and width.
The img has the same width but a lower height.


<style>
#box {
   width: 164px;
   height: 94px;
   border: 1px solid red;
}
</style>

<div id='box'>
   <a href='#'><img src='#'></a>
</div>

how can I center verically the img within that div?
using vertical-align and display table-cell is a solution that is not right in IE.
is there any other solution in CSS?
if not, is there any other solution using Javascript?

many thanks!

Hi jones468,

Since your #box div is a fixed height this can be done easily with display:inline-block; and an empty <b> element with a height set on it.

The trick is to set the empty <b> as inline-block so it can take a height. Set that height at 100% and it will base it’s height off of the parent. Then set v-align:middle; on it and the anchor.

The fluid height anchor will then v-align with the <b> element. It works in all browsers. :slight_smile:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>V-Align - Fixed Height Parent</title>

<style type="text/css">
#box {
   width: 164px;
   height: 94px;
   border: 1px solid red;
   text-align:center;
}
#box a, #box b, #box img {
    display:inline-block;
    vertical-align:middle;
}
#box a {
    padding:10px;
    background:lime;
}
#box b { /*reference height for anchor v-align*/
    height:100%;
}
#box img {/*testing without actual image*/
    width:100px;
    height:30px;
    background:blue;
    border:0;
}
</style>

</head>
<body>

<div id="box">
   [B][COLOR=DarkGreen]<a[/COLOR][/B] href="#"><img src="#" alt="Image Alt">[B][COLOR=DarkGreen]</a>[/COLOR][COLOR=Blue]<b></b>[/COLOR][/B]
</div>

</body>
</html>

superb! :slight_smile:
I have replaced <b> with <span> since <b> it is now outdated.

many thanks!!

Glad you found it helpful :slight_smile:

FYI - The <b> element is NOT deprecated with HTML 4 Elements

We use it as an empty element for styling quite frequently.

Whether you want to say <span> or <b> is up to you.

When the <b> is empty it does not effect the semantics, it’s purpose then is a styling hook.

FYI - The <b> element is NOT deprecated with HTML 4 Elements

Not deprecated HTML5 either. Basically, nowhere.

A variation of this based on line-height:


<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Vertically aligned image</title>
<style>
div {line-height:400px;text-align:center;}
img {vertical-align:middle;}
b {display:inline-block;} 
</style>
</head>
<body>
<div>
<img src="logo.png" alt=""><b></b>
</div>
</body>
</html>