14

Possible Duplicate:
How to center div horizontally and vertically

I need to put image in center of html page, both vertical and horizontal ... been trying few stuff but seems to work fine. To get horizontal alignment I used <body style="text-align:center">

and it works fine, but what do with vertical alignment?

regards

Community
  • 1
  • 1
Darko Rodic
  • 1,010
  • 3
  • 10
  • 27
  • 4
    I'm pretty sure this has been answered more than few times in here already. – Joonas Jun 26 '12 at 11:18
  • 2
    http://stackoverflow.com/questions/10296015/how-to-center-div-horizontally-and-vertically – Alvaro Jun 26 '12 at 11:19
  • 1
    Here's an example that works in IE7 (if it matters), unlike the usual `display: table-cell` answers, and with an image of unknown dimensions: http://stackoverflow.com/questions/10998614/ie7-vertically-align-middle-not-working/10998683#10998683 – thirtydot Jun 26 '12 at 11:20
  • before asking questions just give 2 or 3 mints to SO or www.google.com – khurram Jun 26 '12 at 11:37

4 Answers4

23

If:

X is image width,
Y is image height,

then:

img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;
}

But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.

Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.

DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71
Mateusz Kocz
  • 4,492
  • 1
  • 25
  • 27
9

Put your image in a container div then use the following CSS (changing the dimensions to suit your image.

.imageContainer{
        position: absolute;
        width: 100px; /*the image width*/
        height: 100px; /*the image height*/
        left: 50%;
        top: 50%;
        margin-left: -50px; /*half the image width*/
        margin-top: -50px; /*half the image height*/
    }
Danny
  • 468
  • 2
  • 7
2

Hey now you can give to body background image

and set the background-position:center center;

as like this

body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}
Rohit Azad Malik
  • 31,410
  • 17
  • 69
  • 97
1

There are a number of different options, based on what exactly the effect you're going for is. Chris Coyier did a piece on just this way back when. Worth a read:

http://css-tricks.com/perfect-full-page-background-image/

Eamonn
  • 1,338
  • 2
  • 21
  • 53