Search code examples
cssalignmentcentering

CSS: Make an image in the exact middle of the page


I would like to make an image center in the exact middle of the page, so it's centered vertical and horizontal! Can I do that with a 765x741? Thanks!


Solution

  • Yes of cause you can create a static class in CSS like suggested already:

    .centerPic
    {
        position:fixed;
        left: 50%;
        top: 50%;
        margin-left:-382px; /* Static value */
        margin-top:-370px; /* Static value */
    }
    

    But this approach limits your use of other pictures of different sizes. I suggest you set the margin-left and margin-top properties depending on your picture sizes in dynamic javascript instead:

    function SetCenterStyle (objPic)
    {
        objPic.className = "centerPic";
        objPic.style.marginLeft = ( -1 * ( parseInt(objPic.width) / 2 ) ) + "px";
        objPic.style.marginTop = ( -1 * ( parseInt(objPic.height) / 2 ) ) + "px";
    }
    

    (You can then of cause omit the margin-left and margin-top settings in the centerPic class)