Centre image within div

Centre an image horizontally and/or vertically within a containing DIV even if you don’t know the image size.

Recently I needed a solution whereby the image was centred horizontally and vertically within its containing DIV. Seems straight forward until you bring IE into the mix of things. The main problem is if you have an image which is not always a set width/height i.e. a dynamically generated image. Anyway, here you have it a solution that works in all browsers and validates.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Centre image in containing DIV | Dare to Think</title>
<style type="text/css">
.pic-container {
height: 100px;
width: 100px;
margin-bottom: 20px;
}

.pic-container .pic {
width: 100px;
height: 100px;
display: table-cell;
text-align: center;
vertical-align: middle;
background-color: #000;
}

.pic-container .pic * {
vertical-align: middle;
}
-->
</style>
<!--[if lte IE 7]>
<style type="text/css">
.pic span {
display: inline-block;
height: 100%;
}
</style>
<![endif]-->
</head>
<body>
<div class="pic-container">
<div class="pic"><span></span><img src="http://placehold.it/50x100" alt="" width="50" height="100"/></div>
</div>
<div class="pic-container">
<div class="pic"><span></span><img src="http://placehold.it/100x50" alt="" width="100" height="50"/></div>
</div>
<div class="pic-container">
<div class="pic"><span></span><img src="http://placehold.it/50x50" alt="" width="50" height="50"/></div>
</div>
</body>
</html>

Leave a Reply

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