4

I have a simple form that consists of 2 textboxs. I'm just trying to make the form appearing in the middle of the page. There are no any extra elements in the page. By using align="center" the elements does move to the center but it's not the case for vertical-align:middle?

<html>
<body style="vertical-align: middle;">

<form>
<div align="center" style="vertical-align: middle;">
<h1>blabla</h1>
<label>
<span>Username: </span><input id="userName" type="text" name="userName" />
</label><br/>

<label>
<span>Password: &nbsp;</span><input id="passWord" type="password" name="passWord" />
</label><br/>
<input type="button" value="Login" />
</label>

</div>
</form>

</body>
</html>
SuicideSheep
  • 5,260
  • 19
  • 64
  • 117
  • 2
    Please see [this answer](http://stackoverflow.com/questions/16629561/css-vertical-align-middle-not-working) and [this site](http://phrogz.net/css/vertical-align/) for the answer to your question. – josh Oct 18 '13 at 02:40

1 Answers1

4

Use the following CSS, it centers the content both vertically and horizontally.

You need to set the html/body to height:100%, then set the body, or the parent to display:table. After that, set the child to display:table-cell, and vertical-align:middle. That will take care of the vertical alignment. In order to center horizontally, use margin:0px auto;, and set a width on the form.

jsFiddle here

html, body {
    height:100%;
    width:100%;
    margin:0px;
}
body {
    display:table;
    vertical-align:middle;
}
form {
    display:table-cell;
    vertical-align:middle;
    width:240px;
    margin:0px auto;
}

Full screen result here: http://jsfiddle.net/Sjk6m/embedded/result/

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304