What is the best way to center a Bootstrap login form within the viewport?

Struggling to get the login view centered on the screen, no matter what I try. As a newcomer to Bootstrap and coding, it's proving to be a challenge.

Attempts to use align items center and justify haven't yielded the desired result.

<h2 style="padding-top: 50px">Welcome to Portal.</h2>
<hr/>
<h4 style="padding-top: 20px">Please log in to continue.</h4>
<div class="row justify-content-center" style="padding-top: 30px">
    <div class="col-6">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Log in" class="btn btn-primary" />
                    </div>
                </div>
                
                    <p>
                        @Html.ActionLink("Forgot your password?", "ForgotPassword")
                    </p>
            }
        </section>
    </div>
</div>

Desired visual:

https://i.sstatic.net/0S9Jq.png

Resulting appearance:

https://i.sstatic.net/sGPOw.png

Answer №1

To solve the alignment issue with your login section, wrap the login div with a container that has a maximum width. This will ensure that the container is centered on the page.

Instead of using justify-content-center and extra col-6 classes, simply wrap the login section with a container that has a max-width set.

<h2 class="mt-3">Welcome to Portal.</h2>
<hr/>
<div class="container mt-5" style="max-width:400px">
   <h4 class="mt-2">Please log in to continue.</h4>
   <div class="row">
      <section id="loginForm">
         @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
         {
         @Html.AntiForgeryToken()
         @Html.ValidationSummary(true, "", new { @class = "text-danger" })
         <div class="form-group">
            @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
               @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
               @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
            </div>
         </div>
         <div class="form-group">
            @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
               @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
               @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
            </div>
         </div>
         <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
               <div class="checkbox">
                  @Html.CheckBoxFor(m => m.RememberMe)
                  @Html.LabelFor(m => m.RememberMe)
               </div>
            </div>
         </div>
         <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
               <input type="submit" value="Log in" class="btn btn-primary" />
            </div>
         </div>
         <p>
            @Html.ActionLink("Forgot your password?", "ForgotPassword")
         </p>
         }
      </section>
   </div>
</div>

Answer №2

To make the justify-content center work, consider including the d-flex class in your row element.

Answer №3

To vertically center the content from top and bottom, add align-items-center to the row. Don't forget to specify the height for the row.

For horizontal centering, use width: max-content and margin: 0 auto.

Here is an example:

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>asdasd</title>
    <link rel="stylesheet" href="css/general/bootstrap.css">
    <style>

        .row{
            height: 100vh;
        }

        .main_field{
            width: max-content;
            margin:  0 auto;
        }

    </style>

</head>

<body>

    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="main_field">
                <form>
                    <div class="form-group">
                      <label for="exampleInputEmail1">Email address</label>
                      <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
                      <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
                    </div>
                    <div class="form-group">
                      <label for="exampleInputPassword1">Password</label>
                      <input type="password" class="form-control" id="exampleInputPassword1">
                    </div>
                    <div class="form-group form-check">
                      <input type="checkbox" class="form-check-input" id="exampleCheck1">
                      <label class="form-check-label" for="exampleCheck1">Check me out</label>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                  </form>
            </div>
        </div>
    </div>

</body>

</html>

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

Utilizing PHP variables and CSS to dynamically adjust the background color according to various events triggered by SQL data

Hopefully my explanation is clear. <?php $rx_event_color = $rx_image_color = '#FF0000'; if ($a['rx_event_exists'] == 1) { $rx_event_color = '#00FF00'; } if ($a['rx_scanned'] == 1) { $rx_image_color = '#00FF ...

Reduxforms does not rely on preloaded CSS or JavaScript

Currently, I am utilizing MDBootstrap as my primary CSS framework and integrating redux forms to simplify form management. The issue at hand is that the design and style of elements appear different compared to the original static html page layout. Here ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

What is the best way to position the label above the input text in a Material UI TextField component with a Start Adornment?

Struggling to figure out the right Material UI CSS class to style a reusable TextField component? You're not alone. Despite tinkering with InputLabelProps (specifically the shrink class), I can't seem to get it right. Here's the code snippet ...

CSS: Continuous Automated Slide Transitions

What CSS code do I need to incorporate into my code to create a continuous Slider Animation? I want the pictures to slide automatically one by one, with a specified time interval between each slide when not on hover. The hover function is already included ...

Issues with Google Chrome truncating the end of lengthy pages

While working on a website project, I encountered an issue with Chrome where loading a lengthy page results in a strange box covering the bottom portion of the content. Interestingly, the same pages appear fine on Safari and Firefox, indicating that the pr ...

What is the reason for having a space between the <body> and the <html> tags?

Can you explain why there is a gap between the top of the green box and the browser window in Chrome and Firefox? I've tried various CSS configurations to eliminate the apparent space between the html and body elements, but it seems that some padding ...

Check the data from the radio button selection

I am facing an issue with reading the values of radio buttons in a list, all of which have the same id. Despite trying to retrieve the value of each individual radio button, my code only reads the value of the first radio button. <script src="//ajax. ...

Cursor vanishes until mouse movement detected (Chrome browser)

In the HTML page I created, the mouse cursor is initially set to none. However, there are certain circumstances where I need it to switch to crosshair. The issue I am facing is that the cursor does not appear unless the user moves the mouse. If the mouse r ...

Tips for creating animations with JavaScript on a webpage

I created a navigation bar for practice and attempted to show or hide its content only when its title is clicked. I successfully toggled a hidden class on and off, but I also wanted it to transition and slide down instead of just appearing suddenly. Unfort ...

transferring background-image in html between elements

Imagine having a three-level hierarchy HTML code structured like this: <section> <div id="outer"> <div id="inner"> </div> </div> </section> If we set background-image:someImage.jpg to the section, and backg ...

Linking a script to a button in ASP .NET MVC Razor View

I'm struggling to get a button to invoke a script. Here's the button and script: <script> function SubmitClick () { var pid = $(this).data('personid'); var sid = $(this).data('surveyid'); v ...

What steps are needed to successfully integrate bootstrap.js, jquery, and popper.js into a project by using NPM to add Bootstrap?

I've successfully set up a project and incorporated Bootstrap via npm. However, I'm facing challenges in loading the necessary javascript files for Bootstrap components. It's important to note that I am utilizing a Vagrant Box (virtual machi ...

Aligning elements of unknown width within a container of a specified width

Currently struggling to find a resolution to the following issue: Trying to create a navigation bar using a ul element set to a specific width of 530px with multiple li items nested inside. The goal is to have the li items evenly fill the 530px width wit ...

Sticky sidebar panel featuring a stationary content block

I have a sidebar that is set to position:fixed; and overflow:auto;, causing the scrolling to occur within the fixed element. When the sidebar is activated, the element remains static on the page without any movement. My goal: I am looking to keep the .su ...

perform an action if any division element is void of content

Currently, I have a statement that checks if any of the Divs with the ID #Drop are empty. If one is found to be empty, an alert is shown. However, there seems to be an issue where the statement stops working when any div contains content. What I am trying ...

What is the best way to align two elements side by side using flexbox?

After trying to find a solution on this site without success, I realized that my situation is quite unique. I need to avoid changing the HTML code, minimize the use of classes, and refrain from using IDs. The current HTML structure I am working with inclu ...

Printing long contents on Chrome's ion-modal-view is not supported on every page

I have tried various solutions found in articles but have not been successful. Here is an example of one such attempt: @media print { .modal { position: absolute; left: 0; top: 0; margin: 0; padding: 0; visibility: visible; / ...

I aim to arrange three div elements in a single row with varying widths - placing one on the left, another in the center, and the last

I am trying to have three div elements in one row with different widths - one on the left, one in the center and one on the right. The left div should be 160px The center div should be 640px The right div should be 160px My goal is for them to appear se ...

The Bootstrap 4 dropdown menu is extending beyond the page boundary to the right

I'm having an issue with the dropdown menu in my Bootstrap4 navbar. It's extending past the page on the right side and I've tried a few solutions I found online, like adding dropdown-menu-left or drop-left, but they didn't work for me. ...