What is the best way to align a form in the center of a page both horizontally and vertically

Currently, this is the HTML code I am working with:

<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">Connect</button>
        </p>
    </form>
</body>

I attempted the following CSS to center my form but unfortunately it remains off-center:

#form_login {
    left: 50%;
    top: 50%;
    margin-left: -25%;
    position: absolute;
    margin-top: -25%;
}

Answer №1

Using the grid layout is a popular choice, especially when the form is the only element in the body of the document, resulting in shorter and more concise code.

html {
  min-height: 100%;/* occupy full screen height for vertical alignment */
  display: grid; /* alternatively, you can use display:flex if the body is the sole grid cell */
}

body {
  margin: auto;
}
<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">Log In</button>
  </p>
</form>

You can achieve similar results using display:flex: http://codepen.io/anon/pen/yCKuz

html,body {
  height:100%;
  width:100%;
  margin:0;
}
body {
  display:flex;
}
form {
  margin:auto;/* automatic centering both horizontally and vertically with flexbox */
}

Another option is to use display:table: http://codepen.io/anon/pen/LACnF/ (this approach is recommended for emails where table layouts are common)

body, html {   
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}
body {
    display:table-cell;
    vertical-align:middle;
}
form {
    display:table;/* adjusts to fit content */
    margin:auto;
}

Answer №2

To achieve horizontal centering, enclose the form within a DIV tag and apply the align="center" attribute. This will ensure that the form remains centered even if its width changes.

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

UPDATE:

@G-Cyr is correct. The align="center" attribute is now considered obsolete. Instead, you can use the text-align attribute as demonstrated below.

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

This method will center all content inside the parent DIV. Another option is to utilize the margin: auto CSS attribute along with predefined widths and heights. For more details, refer to the provided link.

How to horizontally center a div in another div?

Vertical centering can be a bit trickier. To achieve this, follow these steps:

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;
}

Answer №3

When utilizing a negative translateX/Y, the need for specifying width and height in the style is eliminated, resulting in a more concise code.

#form_login {
    left      : 50%;
    top       : 50%;
    position  : absolute;
    transform : translate(-50%, -50%);
}
<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>


Another option would be to implement display: grid (refer to the full page view)

body {
   margin        : 0;
   padding       : 0;
   display       : grid;
   place-content : center;
   min-height    : 100vh;
}
<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>

Answer №4

Even after simplifying the code, the accepted solution didn't work for my form. If you're facing the same issue, I suggest giving my alternative a shot. Essentially, you keep the Top and Left values at 50% like the original poster did, but offset the form's container with negative margins equal to half of the div's height and width on the top and left sides respectively. This adjustment shifts the center point of the Top and Left coordinates to the middle of the form. It's crucial to specify the height and width of the form (rather than making them relative). For instance, a form div sized at 300x300px and with -150px margins on the top and left will be perfectly centered regardless of window size:

HTML

<body>
    <div class="login_div">
        <form class="login_form" action="#">
        </form>
    </div>
</body>

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

If you're wondering why I included a container for the form, it's because I prefer having the option to place other elements near the form and ensure they are also centered. While unnecessary in this specific scenario, the form container could prove beneficial in different scenarios. I hope this explanation is helpful!

Answer №5

Have you considered utilizing a CSS grid? It's already 2019 and the browser support for it is quite good.

body {
  margin: 0;
  padding: 0;
  background-color: red;
}

.content {
  display: grid;
  background-color: bisque;
  height: 100vh;
  place-items: center;
}
<!DOCTYPE html>
<html>
<body>
<div class="content">
  <form action="#" method="POST">
    <fieldset>
      <legend>Information:</legend>
      <label for="name">Name:</label>
      <input type="text" id="name" name="user_name">
    </fieldset>
    <button type="button" formmethod="POST" formaction="#">Submit</button>
  </form>
 </div>
 </body>
 </html>

Answer №6

If you're looking for a solution that works efficiently, I recommend using bootstrap:

@import url('http://getbootstrap.com/dist/css/bootstrap.css');
 html, body, .container-table {
    height: 100%;
}
.container-table {
    display: table;
}
.vertical-center-row {
    display: table-cell;
    vertical-align: middle;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login Page | ... </title>

<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
</head>

<body>

<div class="container container-table">
<div class="row vertical-center-row">
<div class="text-center col-md-4 col-md-offset-4" style="">
  <form id="login" action="dashboard.html" method="post">

<div class="username">
<div class="usernameinner">
<input type="text" name="username" id="username" placeholder="Login" />
</div>
</div>

<div class="password">
<div class="passwordinner">
<input type="password" name="password" id="password" placeholder="Mot de passe" />
</div>
</div>

<button id="login-button">Connexion</button>

<div class="keep"><input type="checkbox" /> Gardez moi connecté</div>

</form>
</div>
</div>
</div>
</body>
</html>

Answer №7

#form_login {
             height:500px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;  
        }
<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>

Answer №8

html

<form action="/datahand.php">
            <label for="luname" >EnterUserName</label>
            <input type="text" name="luname" class="inusername"  >
            <label for="lpassword" >EnterPassword</label>
            <input type="password" name="lpassword" class="ipassword"  >
        </form>

css style

 hereform
{
position: relative;
top: 50%;
background-color: burlywood;
width: 300px;
height: 200px;
display: block;
text-align: -webkit-center;

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disappearing table borders in print view on Firefox

I have been working on creating a printable table that displays correctly in Chrome. However, when viewed in Firefox, the table borders are not showing up. <body> <table> <tbody> <tr> ...

How can I stop MUI Button from automatically becoming fullWidth?

One of the challenges I encountered was styling a Button component from MUI: export const ButtonStyle = styled((props) => <Button {...props} />)(({ theme }) => ({ marginTop: 8, marginBottom: 8, width: 'auto', borderRad ...

Establishing limits for a division using keyboard commands

Alright, I've decided to remove my code from this post and instead provide a link for you to view it all here: (please disregard any SQL errors) If you click on a Grid-Node, the character will move to that position with boundaries enabled. Draggi ...

Customize Bootstrap 4 Carousel: Set specific data-interval for each slide

I'm facing an issue with setting the data-interval for each slide of the carousel. I came across a JavaScript code snippet on stackoverflow, but it's not functioning as expected. (Twitter Bootstrap Carousel slide duration) In my HTML, each slide ...

Guide to activating the timer specifically on select pages with jQuery Mobile

I've developed a quiz application using jQuery Mobile and I am working on implementing a timer feature. The timer should run from 0 seconds up to 1 hour but only when the user is viewing specific pages, specifically the question pages. The timer is di ...

What could be causing the issue with the 100% height and 100% width not functioning properly on my ASPX page?

The CSS and HTML code work perfectly in an isolated test environment: body, html { height: 100%; min-height:600px; min-width:800px; overflow:hidden; margin:0;padding:0; } html {overflow:auto;} .fill {height:100%; width:100%; backgro ...

Passing PHP value from a current page to a popup page externally: A guide

I'm currently facing an issue at work where there is a repetitive button and value based on the database. I need to extract the selected value from the current page into a pop-up page whenever the corresponding button is clicked throughout the repetit ...

In the realm of HTML Canvas, polygons intricately intertwine with one another

Currently, I am attempting to create multiple polygons from a large JSON file. Instead of being separate, the polygons seem to be connected in some way. https://i.sstatic.net/Ce216.png The project is being developed in next.js. Below are the relevant co ...

Achieving right-aligned buttons in Bootstrap

Is there a way to align a button to the left inside a div that has the class justify-content-center applied? Here is the code I tried: <div class="card-header justify-content-center"> <div> <div class="ml-5"> Text i ...

Issue with importing a file using JQuery causing the click event to not function properly

I have a file named navigation.html located in a directory called IMPORTS <!-- Navigation --> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-ta ...

Utilizing an array of font styles in a single line while maintaining a consistent width

I am creating a simple webpage with fixed width text. Check out this sample HTML: <div id ="wrap"> <h1>An Annoying Heading</h1> <p>Some text some text some text some text some text some text some text some text some text so ...

What's causing ng-show to malfunction in IE11 on AngularJS?

I am experiencing a strange issue with my code - ng-show works perfectly fine on Firefox, but not on IE 11. <div ng-show="isExist" class="panel panel-default"> Here is the relevant code snippet from the controller: $scope.isExist = false; if(user ...

Develop a CSS layout for the specified design

Aiming to achieve a unique layout using dynamic html strings. The challenge arises when transitioning to the second page as the layout does not adjust upward and images cannot be added to the first page. Attempting to implement the following sample code ...

The Razor MVC does not support HTML syntax within an If condition

Here is the code snippet I currently have in one of my MVC views. It seems that within the specified if condition, the HTML code is not being recognized. <table class="table"> <tr class="row h4"> <td>Task</td> ...

Why does Froala Editor not maintain formatting when retrieving data from the database?

I've been using the Froala editor to add content on my website, and it's doing well for inserting data into the database. However, I'm facing an issue when retrieving data from the database as it doesn't maintain the original formatting ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

What strategies can be used to scale up a website's images in proportion to their page views or traffic?

The situation: On my simple HTML website, I have a group of images placed side by side. Each image is connected to a specific article, and when you hover over the image, a detailed description of the linked article pops up in the center of the page. The o ...

The Ajax load() function is malfunctioning

.load() will only function properly when the files are coming from a server, so I anticipate that it will work later once I have it hosted on a server Edit: This code is functional in Firefox but not in Chrome I've been attempting to apply ajax to l ...

The challenge of navigating CSS specificity guidelines

In my CSS file, I have defined two styles for a table with the class "myTable". The first style sets the background color of header cells to gray, while the second style sets the background color of odd rows to blue: .myTable th { background-color: gr ...

"Creating a HTML Table with Merged Cells using colspan and rowspan

Creating an HTML table with a unique layout is my latest project. I envision it to look like this: +-------+---+ | | | +-------+ + | | | +-----+-----+ | | | +-----+-----+ To achieve this, I'm utilizing a colgroup to split t ...