Search code examples
cssalignment

Center align image vertically & horizontally on a web page


I need to display simple under contruction page which has an image let us say 800x700px & i want this image to appear at the center of page both vertically & horizontally,

I tried different approach's but didn't work. Sample html below

<!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>
<style type="text/css">

html, body { height: 100%; width: 100%; }
body { position: relative;  background-image:url('images/bg.jpg');background-repeat:repeat; }
#mydiv { 
    position: absolute;
    height: 100%;
    width: 100%;
    text-align:ceter;
}
</style>
</head>
<body>
</body>
</html>

Solution

  • Check this article out by Chris Coyier on CSS-Tricks. I think it might help out. I ran into the same problem a few days ago and his answer worked for me.

    Centering an image horizontally and vertically

    Basically the idea is, if your image has a set width and height. You can absolute position it from the left and top 50% and then do negative margins equal to half of the width and height to bring it back dead center. They're are other ways to vertically center an image if it doesn't have set dimensions.