Display image in the center if div

Hi,

I have an image size 128x128

I have a div width 200 height 200

I want to set/put the image in the center of the div, how could i do it ?

Could do it a number of ways. One would be to set the div to 128px wide by 128px high and give it 36px padding all way round. Another way is to set the image as a background to the div with the background position as center.

I see thank you.

I just remember I could use text align center for the div and margin 0 auto for the image

Text align will only centre the image horizontally and not vertically. Auto side margins will only work if the image is converted to block display, and again only affects the horizontal position.

http://blakeanthony.net/Center.html

I coded this tutorial for people that need to have images and divs to be centered. You can change the width of the Div and the div will always be centered. Include your images. Mess around with it and see what you can do. :slight_smile:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Linux (vers 1 September 2005), see www.w3.org" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Centering a Div with Images Centered inside</title>
<style type="text/css">
#center {
  margin-left: auto;
  margin-right: auto;
  width:420px;
  height:420px;
  border:1px dotted #111;
  background:#EFEFCC;
  text-align:center;
 }
img {
text-align:center;
height:210px;
width:190px;
border:1px dotted #111;
}
p {
text-decoration:none;
font-size:1em;
}
</style>
</head>
<body>
<div id="center">This block is centered also.
<p><a href="http://www.sitepoint.com"><img src="http://blakeanthony.net/images/welcomes_winter.jpg" alt="Your image is Center" /></a> <a href="http://www.sitepoint.com"><img src="http://blakeanthony.net/images/welcomes_winter.jpg" alt="Your image is Center" /></a></p>
</div>
</body>
</html>


My Example is 100% Valid across all supporting browser’s.:wink:

You are right.

@BlakeAnthony, thanks for the script, however I still can not align the image vertically inside the div, look like I have to use table.

Why not just use padding as I outlined in post #2 ?

  • I have many images with different sizes to display in one formatted div, so I guess I can not use the padding solution

  • I can’t use the background solution either, as why I come up with this question is that I was trying to position the main image in a javascript image slide show, the various size images have different vertical position in the main image div, tending to be aligned top.

I found some hacking for centering here http://ultimorender.com.ar/funkascript/beta/css/vertical_center.htm

Ahh - in your original post you specified sizes, with no indication that these sizes can vary.

Have a look at this article by Paul O’B.