tags:

views:

32

answers:

1

Hi

I need to align a image to the center of the browser window, therefore i created the following css:

@charset "utf-8";
/* CSS Document */
html {
    background-color:#CCCCCC;
}
body {
    margin:0px 0px 0px 0px;
}
img {
    position:absolute;
    border:0px;
    left:50%;
    top:50%;
    margin-left:-156px;
    margin-top:-217px;
}

The problem is however that if you make the browser window very small, the image floats out to the top and the left. Instead it should be fixed in the top left corner, and then give the possibility to scroll to see the rest of the image.

View the problem here: ejlstrup.com

+2  A: 

Try the following css:

img {
    border: 0px;
    margin: auto auto;
}

The problem will be with your negative margins, they are what is causing the image to be pushed to the left out of view. If you use margin: auto auto, it should center the image for you and you won't have to use absolute positioning with percentages.

Edit: Just tested my method and it didn't work as intended. What you can do then (if you don't mind using a div), is to wrap the image in a div. Make the div the size of the image, then the margin: auto auto; will work properly.

Edit2: Credits to Senthil for pointing out that if you set the image display property to block, you don't have to wrap the image in a div for it to center. However, auto isn't working for centering the div vertically, if it needs to be center you can use a percentage (although I'm not sure if this can cause problems with different resolutions).

img {
    border: 0px;
    margin: auto;
    display: block;
}
Marcin
if the solution in the edit has something to do with image being an inline element and div being a block element, you could set the image's display css property to 'block'
Senthil