Creating a perfectly centered card using Bootstrap 4, both horizontally and vertically

I'm struggling to vertically center a card (or container). Although I can center it horizontally, the vertical alignment is proving to be difficult. Despite trying out various code snippets from Stack Overflow and other websites, none of them seem to work. Here is my current code:

<div class="container col-md-3 py-5">
    <div class="card">
        <div class="card-header">
            <h3 class="mb-0">Login</h3>
        </div>
        <div class="card-body">
            <form class="form">
                <div class="form-group">
                    <label for="username">Username:</label> <input  class="form-control" type="text" name="username" id="username" autofocus required >
                </div>
                <div class="form-group">
                    <label for="password">Password: </label> <input class="form-control" type="password" name="user" id="password" required>
                </div>
             </form>
        </div>
    </div>
</div>

Answer №1

[Verified - operational] Utilize flexbox for optimal layout. Explore this example here

Enclose your code within an additional div that includes the following style rules:

display: flex;
align-items: center;
justify-content: center; 
align-conten:center; 
min-height: 100%;  /* serves as a backup for browsers that do not support vh unit */
min-height: 100vh;

This approach should function smoothly.

Complete code with inline style (it is advised to utilize classes instead of directly adding styles via attributes):

<div style=" display: flex; align-items: center; justify-content: center; align-conten:center; min-height: 100%; min-height: 100vh;">
<div class="container col-md-3 py-5" style="height: 200px; width:200px">
<div class="card">
    <div class="card-header">
        <h3 class="mb-0">Login</h3>
    </div>
    <div class="card-body">
        <form class="form">
            <div class="form-group">
                <label for="username">Username:</label> <input class="form-control" type="text" name="username" id="username" autofocus="" required="">
            </div>
            <div class="form-group">
                <label for="password">Password: </label> <input class="form-control" type="password" name="user" id="password" required="">
            </div>
         </form>
    </div>
</div>
</div>
</div>

Answer №2

Give this code a shot, I think it will do the trick for you

.container.py-5{
    position: fixed; //or relative
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
}

Answer №3

Ensure your body has the Bootstrap 4 classes d-flex align-items-center and set its height to 100vh;

body{
  height:100vh;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<body class="d-flex align-items-center">
    <div class="container col-md-3 py-5">
        <div class="card">
            <div class="card-header">
                <h3 class="mb-0">Login</h3>
            </div>
            <div class="card-body">
                <form class="form">
                    <div class="form-group">
                        <label for="username">Username:</label> <input  class="form-control" type="text" name="username" id="username" autofocus required >
                    </div>
                    <div class="form-group">
                        <label for="password">Password: </label> <input class="form-control" type="password" name="user" id="password" required>
                    </div>
                 </form>
            </div>
        </div>
    </div>
</body>

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

Modifying the position of an image in Flask

I am trying to center an image on my webpage and have attempted the following code: <image height="300px" width="300px" src="{{url_for('static',filename = 'img/Rasd.jpeg')}}" > Visit this webpage fo ...

My preference is for the flex box to expand in width (sideways) without increasing in height (up and down)

Is there a way for flex items to expand in width but only in height when necessary? I enjoy using flexbox, but I find it frustrating that all flex items in a row grow to the same height even when there isn't enough content to fill them, resulting in a ...

Using JQuery to create an animated slideToggle effect for a multicolumn list

I have a large list where each li element has a width of 33%, resulting in 3 columns: computers monitors hi-fi sex-toys pancakes scissors Each column contains a hidden UL, which is revealed through slideToggle on click. JQuery $('.subCate ...

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info-> ...

I have developed a custom jQuery carousel that includes functionality to start and stop the carousel based on specific conditions

I have set up a jQuery carousel that moves to the left when a checkbox is checked, but I need it to stop moving when the checkbox is unchecked. Can someone help me achieve this? $("#checkBox").click(function(){ if($(this).prop("checked") == true){ ...

Despite the presence of ngIf, the tab is still displayed

Even though ngIf is used, the FirstTab remains visible. How can I completely remove the tab? Here is the code snippet: <tabs style="min-height:auto"> <tab tabTitle="FirstTab" *ngIf="str=='dp'" > <first-tab> ...

Update the index of each list object and then add them to the Angular controller

Currently, I am working on integrating Spring with AngularJS. In my setup, I have a Spring controller returning a List object to the Angular controller. When I print the List in the Spring controller console, it appears as follows: [org.com.pro.dto.MyDTO ...

What are the advantages of using REM instead of PX?

When is it ideal to choose rem over px units in CSS? Many articles advocate for using REM to accommodate user preferences, particularly when it comes to font size. However, the focus tends to be solely on font size rather than considering other aspects lik ...

Having a challenge with aligning a form in a view, as neither bootstrap nor plain CSS seem to be helping with centering it correctly

What techniques can I use to center this form properly in both bootstrap and plain CSS? So far, I have been able to center some parts of it, but when I try to center others, they shrink and create a mess. When I use bootstrap to center the elements, they b ...

Creating full-width divs using BootstrapLearn how to easily create full-width div

Bootstrap is being utilized in my current project. I have been creating divs inside columns, but they are not extending to the full width of the columns. Below is a snippet of the code: <!DOCTYPE html> <html lang="en"> <head> ...

Opt for filling background image instead of stretching it when the screen is resized

My background image resizes with the screen height but stretches when I change the width. The content that should appear below it completely covers the image. This is my current code: HTML: <div id="bg"> <img src="http://placehold.it/2560x1 ...

Displaying MongoIds in HTML output for the user

Currently, I am in the process of developing a web application that utilizes MongoDB as its database management system. One challenge I am facing is finding a way to accurately identify which object the user has selected from a list on the screen, and the ...

Angular has the capability to rewrite URLs in CSS, providing a unique way

An issue arises in Angular when using a base set and html5mode with SVGs. This causes things like filter: url(#url) to be rewritten as filter: url(/base/#url). https://github.com/angular/angular.js/issues/8934 Disabling html5 mode and removing the base d ...

Tips for designing a flexible structure with 2 columns, each containing an additional 2 columns within

Is it possible to create a 4-column responsive layout? | column left | column right | column left| column right| I would like to achieve a single row layout on larger devices as shown below | column left | column right | column left| column right| an ...

Retrieving the HTML Head Element from Internet Explorer's Document Object Model

For extracting the HTML body of a document, I am familiar with utilizing the IHTMLDocument2 interface by invoking the get_body member function. However, obtaining the head seems to be more challenging. Is there an alternative method since the IHTMLDocumen ...

Organize the attributes of components on the following line in Visual Studio Code

Is there a method to configure the VS code formatter for Angular 2+ templates to ensure that attributes are wrapped in a new line? I prefer this formatting: <app [input1]="input1$ | async" [input2]="input2$ | async" (inputChanged)="set ...

Tips for setting up an automated system to check feeds

While I have experience parsing and setting up databases in PHP, I am now faced with the challenge of constantly monitoring an XML feed for a specific string within one of the tags. Each time this string is detected, I need to add the entire XML item (incl ...

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

Issue with mobile.changePage() function not executing as expected

I created a basic code that generates a "Splash screen". For storing my data, I am utilizing localstorage. When I first load it, I retrieve data from a URL and I am able to navigate to different pages using $.mobile.changePage(). However, if the data is a ...