Center an image inside a div

In many situations we want to put an image at the center of a Div. The following program display an image at the center of a Div element.








Source Code

<!DOCTYPE html> <html > <head> <style type="text/css"> #holder { position:absolute; width:100%; height:100%; } #holder img { display: block; margin-left: auto; margin-right: auto; } </style> </head> <body> <div id="holder"> <img src="duck.png"> </div> </body> </html>

horizontally and vertically centering an image in a Div

The following program shows how to display an image vertically and horizontally at the center of a Div element.

Source Code

<!DOCTYPE html> <html > <head> <style type="text/css"> #holder { background:url(duck.png) no-repeat center center; height:300px; width:300px; border: 5px solid red; } </style> </head> <body> <div id="holder"> </div> </body> </html>

Absolute Center an Image inside a Div

This is another easy way to center an image vertically and horizontally at the center of a Div element

Source Code

<!DOCTYPE html> <html > <head> <style type="text/css"> #holder { display:table-cell; vertical-align:middle; text-align:center; height:300px; width:300px; border: 5px solid blue; } </style> </head> <body> <div id="holder"> <img src="duck.png"> </div> </body> </html>