开发者

Image floating out of screen

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 sma开发者_开发知识库ll, 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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜