Learning
Learning

Reputation: 20011

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>

Upvotes: 3

Views: 26545

Answers (3)

Aminah Nuraini
Aminah Nuraini

Reputation: 19186

This CSS can center your image regardless of the length.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

The secret is in the transform. Without it, it only puts the top left pixel of the image in the center, not the whole image beautifully.

Upvotes: 13

Matt Whitehead
Matt Whitehead

Reputation: 1811

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.

Upvotes: 7

KBN
KBN

Reputation: 2974

You didn't have the ID set for the div, I have edited that, once that's done, the image will be horizontally aligned. Also, mydiv need not be positioned "absolute".

To vertically align the picture, the best solution without using javascript would be to give the img a margin-top with %.

#mydiv {
 text-align: center;
}

#mydiv img {
 margin-top: 15%;
}

Upvotes: 1

Related Questions