CSS : center form in page horizontally and vertically

css, html

Solution

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.

<div align="center"><form id="form_login"><!--form content here--></form></div>

UPDATE

@G-Cyr is right. `align="center"` attribute is now obsolete. You can use `text-align` attribute for this as following.

<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>

This will center all the content inside the parent DIV. An optional way is to use `margin: auto` CSS attribute with predefined widths and heights. Please follow the following thread for more information.

How to horizontally center a in another ?

Vertical centering is little difficult than that. To do that, you can do the following stuff.

html

<body>
<div id="parent">
    <form id="form_login">
     <!--form content here-->
    </form>
</div>
</body>

Css

#parent {
   display: table;
   width: 100%;
}
#form_login {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

Problem

How can i center the form called form_login horizontally and vertically in my page ? Here is the HTML I'm using right now: ``` <body> <form id="form_login"> <p> <input type="text" id="username" placeholder="username" /> </p> <p> <input type="password" id="password" placeholder="password" /> </p> <p> <input type="text" id="server" placeholder="server" /> </p> <p> <button id="submitbutton" type="button">Se connecter</button> </p> </form> </body> ``` I have tried to do the following css but my form is never centered : ``` #form_login { left: 50%; top: 50%; margin-left: -25%; position: absolute; margin-top: -25%; } ```

Original source

Related problems