Help Me/Question Css Howto: Put An Image Exactly In The Center Of The Page

Status
Not open for further replies.

Dragos

Yellow Belt
I got this problem a couple of days ago, and I want to share the answer with you.
I wanted to have a page with an image on it, and I wanted the image to be exactly in the center/middle of the page, no matter the screen resolution.
First, here is how you do it for a image with size 600px/600px:

On the css file you need to have the following:
HTML:
.centered-box {
    width: 600px;
    height: 600px;
    left: 50%;
    top: 50%;
    margin-top: -300px;
    margin-left: -300px;
    position: fixed;
}

* html .centered-box { 
    position:absolute;
}
And on the html page just add

HTML:
<div class="centered-box"> 
<img src="image.jpg"/> 
</div>
And now to explain the CSS code, so you can make it suitable for you:

HTML:
.centered-box {
    width: 600px; // This is the width of your image
    height: 600px; // This is the height of your image
    left: 50%;
    top: 50%;
    margin-top: -300px; // This value needs to be exactly half of your image's height
    margin-left: -300px; // This value needs to be exactly half of your image's width
    position: fixed;
}

* html .centered-box { 
    position:absolute;
}
 
L

lqyromeo

Sorry guy, maybe you are puzzled, the width should be belong the DIV, not iamge, is it ture?
 
Status
Not open for further replies.
Top