Thursday, May 20, 2010

Centering an Image on a web page

It's harder than you think...
You want to place a "box" and an image on a web page. AND, you want them centered.

Method #1: Absolute, Auto and 0 (zero)

Make the Box and the image have the property and value position: absolute; and Use Margin: auto; but set the Top, Right, Bottom and Left positions to 0 (zero). Check out the embedded source!

Check to see if this works in all browsers!

Method #2: The 50% Solution



Using Absolute, 50% Percent and subtract 1/2 (50%) of the width and height of the image
Make the Box and the image have the property and value position: absolute; set the Top, Right, Bottom and Left positions to 50% and subtract from margin-top, margin-right, margin-bottom and margin-left 1/2 (50%) of the width and height of the image in pixel units. Check out the embedded source!

Method #3: Display Block



Tricky... The key to centering an image on a web page is that by default an image is an inline element.


"Inline Elements always begin on the same line. Height, line-height and top and bottom margins can’t be changed. Width is as long as the text/image and can’t be manipulated!"
Unless you change the image to act like a block element using the Property and Value display:block;


You could put the image in a div, but why add a div when you don't need it?


Click on the above images to see the actual web pages. PLease report if the above works in your browsers!  Thanks

No comments:

Post a Comment