How to align a form in center in bootstrap?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, I am going to show you. How to align a form in center in bootstrap with code example.

Here, we will use .form-group class to make a form in center.

In the example we’ll learn how to align a form, so that it always remains in the center of the page, independently from the device or screen size.

Let’s look at the following example to understand how it basically works:

<!doctype html>
<html lang="en" class="h-100">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>How to Align Responsive Image in Center in Bootstrap</title>
      
  </head>
  <body class="h-100">

    <div class="container h-100">
      <div class="row h-100 justify-content-center align-items-center">
          <div class="col-10 col-md-8 col-lg-6">
              <!-- Form -->
              <form class="form-example" action="" method="post">
                    <h1>Bootstrap 4: Align Center</h1>
                    <p class="description">A tutorial on how to align a "form" in Bootstrap 4 and 5.</p>
                    <!-- Input fields -->
                    <div class="form-group">
                        <label for="username">Username:</label>
                        <input type="text" class="form-control username" id="username" placeholder="Username..." name="username">
                    </div>
                    <div class="form-group">
                        <label for="password">Password:</label>
                        <input type="password" class="form-control password" id="password" placeholder="Password..." name="password">
                    </div>

                    <button type="submit" class="btn btn-primary btn-customized mt-4" >Login</button>
                </form>
              <!-- Form end -->
          </div>
      </div>
  </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

  </body>
</html>

As you can see, we also add the class “h-100” to the first two div parents of the form, the “container” and “row” divs.

In the above code, we have used .form-group class to of align a form in center in bootstrap.

Check the output of the above code example.

Bootstrap, Form

This is the final result.

All the best 👍