center an image inside a div

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi everyone:

I have a div and there is an img inside. The image is much smaller
compared with div. So I would like to center the img inside the div.
Here is my code:

<div align="center" id="myCanvas" style="border:0px,
onmousemove = "mouseTrace();" onmousedown = "traceMouseDown();"
onkeydown="ctrlKeyDown();" onkeyup="ctrlKeyUp();">
<img id="p" style="vertical-align:middle;vertical-align:center;"

As you can see, I tried many things. But the small image is still on
the top-left corner of the div. What did I do wrong?



Re: center an image inside a div

Quoted text here. Click to load it

Use text-align: center on the div. Img is inline by default, which means
it behaves a bit like text. Centering text is something you do on the
container-- think about it, you couldn't reasonably centre some words
but not others in a paragraph.

Or you can make the img display: block and then centre it with
margin-left: auto and margin-right: auto.

Avoid deprecated presentational attributes like align="" etc., they only
make things more confusing.

Re: center an image inside a div


I have a test here, centering a unkown height pic into a div

I hope this will help you



Site Timeline