CSS : center form in page horizontally and vertically

后端 未结 6 1612
执念已碎
执念已碎 2020-12-13 01:33

How can i center the form called form_login horizontally and vertically in my page ?

Here is the HTML I\'m using right now:


    
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 02:00

    The accepted answer didn't work with my form, even when I stripped it down to the bare minimum and copied & pasted the code. If anyone else is having this problem, please give my solution a try. Basically, you set Top and Left to 50% as the OP did, but offset the form's container with negative margins on the top and left equal to 50% of the div's height and width, respectively. This moves the center point of the Top and Left coordinates to the center of the form. I will stress that the height and width of the form must be specified (not relative). In this example, a 300x300px form div with margins of -150px on the top and left is perfectly centered no matter the window size:

    HTML

    
        
    
    

    CSS

    .login_div {
        position: absolute;
    
        width: 300px;
        height: 300px;
    
        /* Center form on page horizontally & vertically */
        top: 50%;
        left: 50%;
        margin-top: -150px;
        margin-left: -150px;
    }
    
    .login_form {
        width: 300px;
        height: 300px;
    
        background: gray;
        border-radius: 10px;
    
        margin: 0;
        padding: 0;
    }
    

    JSFiddle

    Now, for those wondering why I used a container for the form, it's because I like to have the option of placing other elements in the form's vicinity and having them centered as well. The form container is completely unnecessary in this example, but would definitely be useful in other cases. Hope this helps!

提交回复
热议问题