Bilbo Baggins Bilbo Baggins - 2 months ago 13
HTML Question

Centering a form horizontally and vertically

I have looked for a solution to this for around half a day. I am just starting web design and I need to center a form horizontally and vertically. Right now it is in the top left-hand corner. Please do not mind the bad code I am going to tidy it up soon.



form {

display: table-cell;
text-align: center;
vertical-align: middle;

}


.trans {

background:rgba(1,1,1,0.6);

}

body {

background-image: url(wallpaper.jpg);

}

.text {



}

.box {

display: table;
width: 100%;

}

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="icon" type="image/ico" sizes"32x32" href="pths_logo32x.png">
<title>Peq Anon</title>

</head>

<body>

<div class="container">
<form>
<input class="trans text" type="text" name="Password">
<button type="submit" onclick="#">Submit</button>
</form>
</div>



</body>
</html>




Answer

Here is a simple solution: wrap your form in a container div and use display: flex property to set the alignment.

Try this:

<div class="container">
<!-- the rest of your code comes here -->
</div>

And for the CSS

.container {
  display: flex;
  justify-content: center; /* center horizontally */
  align-items: center; /* center vertically */
}

Edit

You have to make sure that the height of your body, html and container elements are all set to 100%.

Look at this fiddle for an example: Fiddle