Aligning content vertically in Bootstrap 4 so it is centered

I've been struggling to center my Container in the middle of the page using Bootstrap 4. I haven't had much luck so far. Any suggestions would be greatly appreciated.

You can check out what I have so far on Codepen.io and experiment with it to see if you can find a solution. At this point, I'm running out of ideas...

var currentAuthor = "";
var currentQuote  = "";
function randomQuote() {
  $.ajax({
      url: "https://api.forismatic.com/api/1.0/?",
      dataType: "jsonp",
      data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
      success: function( response ) {
        $("#quote-content").html('<h2 id="quote-content" class="display-5"><i class="fa fa-quote-left" aria-hidden="true"> ' + response.quoteText + ' <i class="fa fa-quote-right" aria-hidden="true"></i></h2>');
        $("#quote-author").html('<p id="quote-author" class="lead"><em>' + response.quoteAuthor + '</em></p>');
        
        currentAuthor = response.quoteAuthor;
        currentQuote  = response.quoteText
      }
  });
}

function openURL(url){
  window.open(url,'Share', 'width=550, height=400, toolbar=0, scrollbars=1 ,location=0 ,statusbar=0,menubar=0, resizable=0');
}

function tweetQuote(){
      openURL('https://twitter.com/intent/tweet?hashtags=quotes,freecodecamp&related=freecodecamp&text=' + encodeURIComponent('"' + currentQuote + '" - ' + currentAuthor));
}

$(document).ready(function () {
    randomQuote();

    $("#get-another-quote-button").click(function(){
        randomQuote();
    });

   $('#tweet').on('click', function() {
       tweetQuote();
   });
});
html, body {
  background-image: url("https://www.mylinea.com/wp-content/uploads/beautiful-trees-stock-photo-055.jpg");
    background-color: #17234E;
    margin-bottom: 0;
    min-height: 30%;
    background-repeat: no-repeat;
    background-position: center;
    -webkit-background-size: cover;
    background-size: cover;
}


.btn-new-quote {
    color: #0C0C0D;
    background-color: transparent;
    border-color: #414147;
}

.btn-new-quote:hover {
    color: #0C0C0D;
    background-color: #9A989E;
    border-color: #0C0C0D;
}

#tweet {
    color: RGB(100, 100, 100);
}

#tweet:hover {
    color: RGB(50, 50, 50);
}


.jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    opacity: .85;
    border-color:  RGB(50, 50, 50);
    padding-bottom: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<div class="container">
    <div class="row justify-content-center align-self-center">
        <div class="col-sm-6">
            <div class="jumbotron vertical-center text-center">
                <h2 id="quote-content" class="display-5"><i class="fa fa-quote-left" aria-hidden="true"></i><i class="fa fa-quote-right" aria-hidden="true"></i></h2>
                <p id="quote-author" class="lead"><em></em></p>
                <hr class="my-2">
                <div class="row align-items-center justify-content-between">
                    <div class="col-sm-1-4 text-left">
                        <a id="tweet" href="#">
                            <h2 class="display-4"><i class="fa fa-twitter" aria-hidden="true"></i></h2>
                        </a>
                    </div>
                    <div class="col-sm-1-4 text-right">
                        <button id="get-another-quote-button" type="button" class="btn btn-outline-secondary  btn-new-quote">Don't Quote Me on This...</button>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

Answer №1

Attention! Vertical alignment is dependent on the parent element's height

If the parent container of the element you are trying to vertically center does not have a defined height, then none of the vertical centering methods will be effective!

Let's dive into vertical centering techniques...

Bootstrap 5 (Updated 2021)

Bootstrap 5 still relies on flexbox layout so vertical centering can be achieved using familiar methods from Bootstrap 4. Options include applying classes like align-items-center, justify-content-center, or utilizing auto margins on the flexbox parent containers (row or d-flex).

  • Use align-items-center on a flexbox row parent (row or d-flex)
  • Apply justify-content-center to a flexbox column parent (d-flex flex-column)
  • Utilize my-auto within a flexbox parent

Achieving Vertical Centering in Bootstrap 5


Bootstrap 4

You can leverage the new flexbox & size utilities in Bootstrap 4 to make the container full-height and utilize display: flex. These methods do not require additional CSS (except ensuring that the height of the container (e.g., html,body) is set to 100%).

Method 1 - Using align-self-center on a flexbox child element

<div class="container d-flex h-100">
    <div class="row justify-content-center align-self-center">
     Content centered vertically
    </div>
</div>


More Resources on Bootstrap 4 Vertical Centering

With the introduction of flexbox and other useful features in Bootstrap 4, there are various approaches available for achieving vertical alignment.

1 - Vertical Centering Using Auto Margins:

An alternative technique for vertical centering involves using my-auto. This approach centers the element within its container. For example, setting h-100 makes the row full height, and my-auto ensures vertical centering within the col-sm-12 column.

<div class="row h-100">
    <div class="col-sm-12 my-auto">
        <div class="card card-block w-25">Card</div>
    </div>
</div>

Demo of Vertical Centering Using Auto Margins

my-auto sets margins along the vertical y-axis and is equivalent to:

margin-top: auto;
margin-bottom: auto;

Remember the Importance of Setting Heights!

Always keep in mind that vertical centering is tied to the height of the parent element. If you aim to center elements on an entire page, the following CSS approach is crucial:

body,html {
  height: 100%;
}

Alternatively, use min-height: 100vh (or min-vh-100 in Bootstrap 4.1+) on the container element. A defined height for the parent/container is necessary to facilitate centering of child elements.

For more details, refer to:
Vertical Alignment in Bootstrap 4
Vertical and Horizontal Alignment with Bootstrap

Answer №2

To achieve perfect horizontal and vertical alignment using bootstrap version 5 or newer, simply utilize the following code snippet.

<div class="vh-100 d-flex justify-content-center align-items-center">
  <h1>Content perfectly centered vertically and horizontally!</h1>
</div>

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

Answer №3

To center your container vertically, apply the following style to the parent container by making it a flexbox and using align-items: center:

.wrapper {
  display: flex;
  align-items: center;
}

Check out the updated code on CodePen

Answer №4

Using the following Bootstrap 4 classes proved to be quite useful in resolving this issue:

<div class="col text-center justify-content-center align-self-center">
    <img width=3rem src=".." alt="...">
</div>

Answer №5

Since none of the solutions above helped me, I decided to share my own approach.

Purpose: To align a div both vertically and horizontally on a webpage using Bootstrap 4 flexbox classes.

Step 1: Begin by setting your outermost div's height to 100vh. This ensures that the height is equal to 100% of the viewport height. Without this step, the alignment won't work properly. Setting it to 100% would be relative to its parent, which could cause issues if the parent isn't the full height of the viewport. In the example below, I set the Body to 100vh.

Step 2: Make the container div a flexbox container by adding the class d-flex.

Step 3: Horizontally center the div using the class justify-content-center.

Step 4: Vertically center the div with the align-items-center class.

Step 5: Preview the page to see your vertically and horizontally centered div.

It's important to note that you don't need any special class on the centered div itself (the child div).

<body style="background-color:#f2f2f2; height:100vh;">

<div class="h-100 d-flex justify-content-center align-items-center">
    <div style="height:600px; background-color:white; width:600px;">
</div>

</div>

</body>

Answer №6

This is how I implemented it using Bootstrap version 4.3.1:

<div class="d-flex vh-100">
  <div class="d-flex w-100 justify-content-center align-self-center">
    Centered content
  </div>
</div>

Answer №7

.header {
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
}

Answer №8

<div class="row">
  <div class="col-md-6">
     <img src="/assets/images/ebook2.png" alt="" class="img-fluid">
  </div>
  <div class="col-md-6 my-auto">
     <h3>Title</h3>
     <p>A brief description.</p>
   </div>
</div>

The key element here is

<div class="col-md-6 my-auto">
, where using the my-auto class will center the content within the column. It comes in handy when aligning text next to an image of varying sizes, as seen in the code snippet above.

Answer №9

After testing all the suggestions provided, I discovered a key difference between h-100 and vh-100. Here is the code snippet for my solution:

      <div className='container vh-100 d-flex align-items-center col justify-content-center'>
        <div className="">
             ...
        </div>
      </div >

Answer №10

<div class="col-lg-5 col-sm-5 offset-1 d-flex">
            <div class="offer-txt justify-content-center align-self-center">
                <span class="inner-title">Special Deal</span>
                <h2 class="section-title">Today’s Featured Item</h2>
                <p>Early one morning, Gregor Samsa awoke to find himself transformed into a bug in his bed. He lay on his armoured back, able to see his brown belly when he lifted his head slightly.</p>
            </div>
        </div>

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

Answer №11

To center elements vertically in Bootstrap 4 (beta), you can use the align-middle class. For more details, check out the Bootstrap 4 Documentation on Vertical alignment:

You can adjust the vertical alignment of elements using the vertical-alignment utilities provided by Bootstrap 4. Keep in mind that vertical-align will only affect inline, inline-block, inline-table, and table cell elements.

Choose from classes like .align-baseline, .align-top, .align-middle, .align-bottom, .align-text-bottom, and .align-text-top depending on your specific needs.

Answer №12

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href"https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
  <script src"https://maxcdn.bootstrapcdn.com/bootstrap/.2.1/js/bootstrap.min.js"></script>
</head>
<body>
  
<div class="container">
    <div .="row align-items-center justify-content-center" style=.height:100vh;">
         <.div>Center Div Here</div>
    </div>
</div>

Answer №13

Utilizing vertical alignment with Bootstrap 4 classes:

Approach 1:

Parent: d-table

AND

Child: d-table-cell & align-middle & text-center

Example:

<div class="tab-icon-holder d-table bg-light">
   <div class="d-table-cell align-middle text-center">
     <img src="assets/images/devices/Xl.png" height="30rem">
   </div>
</div>

If you want the parent to be circular:

<div class="tab-icon-holder d-table bg-light rounded-circle">
   <div class="d-table-cell align-middle text-center">
     <img src="assets/images/devices/Xl.png" height="30rem">
   </div>
</div>

The two custom CSS classes are as follows:

.tab-icon-holder {
  width: 3.5rem;
  height: 3.5rem;
 }
.rounded-circle {
  border-radius: 50% !important
}

Final usage example can be like:

<div class="col-md-5 mx-auto text-center">
    <div class="d-flex justify-content-around">
     <div class="tab-icon-holder d-table bg-light rounded-circle">
       <div class="d-table-cell align-middle text-center">
         <img src="assets/images/devices/Xl.png" height="30rem">
       </div>
     </div>

     <div class="tab-icon-holder d-table bg-light rounded-circle">
       <div class="d-table-cell align-middle text-center">
         <img src="assets/images/devices/Lg.png" height="30rem">
       </div>
     </div>

     ...

    </div>
</div>

Approach 2: You can use the following:

Parent: h-100 d-table mx-auto

AND

Child: d-table-cell align-middle

Approach 3:

You can use the following:

Parent: d-flext align-items-center

If you want the content to be horizontally centered too:

Parent: d-flex align-items-center justify-content-center

Answer №14

Exploring the symbiosis between Bootstrap 5 and Blazor Web Assembly:

<div class="d-flex align-items-center justify-content-center min" style="height: 50vh">
<button class="btn btn-outline-success mx-2">Register</button>
<button class="btn btn-outline-primary mx-2" style="width:123.44px">Login</button></div>

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

Answer №15

/*Don't forget to include a height of 100vh */

Middle

Answer №16

Apply the .my-auto CSS class from Bootstrap 4 to center your div.

Answer №17

To ensure your content is displayed within a flexbox container that spans 100% of the height, add the h-100 class. Next, you can center the content using the justify-content-center class.

<section class="container h-100 d-flex justify-content-center">
    <div class="jumbotron my-auto">
        <h1 class="display-3">Welcome to Iceland!</h1>
    </div>
</section>

Answer №18

With the latest version of Bootstrap, aligning a card is a breeze. Check out this example below where we simply need to specify the width of the card, with the rest of the alignment taken care of by Bootstrap 5 classes.

<div class="container d-flex vh-100">
  <div class="row mx-auto">
    <div class="col align-self-center p-4">
      <div class="card rounded-3 shadow-sm p-3" style="width:400px">
        <div class="card-body">
          <h1>I'm perfectly centered both vertically and horizontally</h1>
        </div>
      </div>
    </div>
  </div>
</div>

Answer №19

Featuring custom classes compatible with Bootstrap versions 2, 3, 4, and 5, designed to work seamlessly with any height and width requirements.

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

.d_tbl{
  display:table;
  width:100%;
  height:200px;
}

.d_tblCel{
  vertical-align: middle;
  display: table-cell;
  text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <div class="d_tbl" style="background-color:antiquewhite">
    <div class="d_tblCel">
      <h3>Centered horizontally and vertically</h3>
      <p>for all bootstrap versions with only two custom classes</p>
    </div>
  </div>
</div>

</body>
</html>

Answer №20

Using Bootstrap 4.1.3:

I came across a solution that worked well for me when I needed to center a Bootstrap badge inside a container > row > column next to an h1 heading.

The simple CSS code that did the trick was:

.my-valign-center {
  vertical-align: 50%;
}

Alternatively, you could use:

<span class="badge badge-pill" style="vertical-align: 50%;">My Badge</span>

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

In Safari, my layout is disrupted by the mere mention of the word 'City'

There's something strange happening in Safari that I can't quite figure out. Here's how my layout looks in Chrome: https://i.sstatic.net/lPhnP.png But when viewed in Safari, it looks like this: https://i.sstatic.net/IMnQb.png For some r ...

Ways to achieve perfect alignment for SVG text within its container, as opposed to stretching across the entire webpage

Recently, I've been working on a customizable photo frame designer using SVG. One of the key features allows users to add their own text to the frame. To achieve this, I'm utilizing jQuery's .keyup function. However, the issue I'm facin ...

How can you achieve a vertical list display for a label while preserving its inline-block properties?

I have chosen to use labels for my radio buttons because I enjoy the convenience of being able to click on the text to select the option. However, I want these labels to appear in a vertical list format. Currently, they are displaying as blocks, causing th ...

"Engaging with the touchscreen inhibits the triggering of click

Within this div, I have implemented touch-action:pan-y;. Surrounding this div is an anchor tag. If you click on the div, the link will successfully redirect. However, if you swipe on the div and then click, the link won't work on the first attempt bu ...

Expanding the visual in a spacious display with the help of ng-carousel from the Bootstrap framework

I have created a slider with multiple images on a website using Angular 4. The slider is displayed in a small area of the webpage and I would like to add a feature where the user can click on an image to view it in a larger screen or window. This could i ...

Is the table scrollable within the tbody tag?

Is it possible to create a table with a scrollbar on the right side using only CSS and without any plugins like jQuery? Additionally, I want the table header to remain fixed in place. What steps do I need to take to achieve this functionality? ...

Utilize jQuery to dynamically add a CSS class to a button

When using jQuery to create dynamic buttons, is there a way to add a CSS class to the button during creation without needing an extra line of JavaScript to add the class afterwards? Below is a example code snippet: $.each(data, function (index, value) { ...

Distinguish the disparities between mobile and desktop devices

I need a solution for adjusting the layout of a component based on the device it is viewed on. For mobile devices, I want the content to stack vertically like in this example: https://codesandbox.io/s/material-demo-forked-ktoee?file=/demo.tsx. However, o ...

Unable to change the bootstrap variables

I have been attempting to customize Bootstrap colors by referring to the documentation, but unfortunately, no changes are being applied. My setup includes react-bootstrap@2 and bootstrap@5 Below is my main sass file: // The inclusion of these two imports ...

Creating a display of divs that flow from left to right in each row, and then stacking the rows from bottom to top using CSS and jQuery

My current dilemma involves a collection of divs that must be displayed in a specific order, but with a rather intricate layout. Essentially, this is the structure of my HTML: <div> <div class="box">1 (first in list)</div> <di ...

Utilize multiple background images in CSS with a set of three unique images

I have inserted three images into the background of my website's body. Two of them are displaying correctly (one with repeat-y), but the third one is not working. I've tried searching a lot but couldn't find a solution. body { backgr ...

Tips on relocating the input position to the top

Currently, I have a text input that is centered horizontally when typing text. However, I want it to be positioned at the top instead. See the following code: height: 143px; width: 782px; font-family: 'Roboto Mono'; background: #FFFFFF; border ...

Spinning divs using JavaScript when the mouse hovers over them, and then returning them to their original position when the mouse moves

I am looking to create a functionality where a div rotates when the mouse enters it and returns to its original position when the mouse leaves. Everything works fine when interacting with one div, but as soon as I try hovering over other divs, it starts gl ...

Invisibility Problem

As a newcomer to web design, this is only the second website I have ever created. However, I am facing an issue with my Nav bar that I cannot seem to resolve. I want my "Other Pages" section to be visible when the screen size is below 600px and hidden when ...

Use jQuery to permit only numeric characters and the symbol "-" to be entered into a textbox

I have been working on a JQuery script that only allows users to input numbers in a text field. However, I am now trying to modify the code to also allow users to enter "-" (hyphen), but so far it's not working as expected. If anyone can provide assis ...

What is causing the left scroll to not work with negative values?

My design features three blocks stacked on top of each other with an additional block at the bottom below the middle. Left <--------> Middle<---------->Right -----------------Bottom------------------ I have a couple of queries. Why is scr ...

What is the reason behind Facebook's use of margin-left: -9999px to conceal elements?

While experimenting with firebug on Facebook's stream, I stumbled upon an interesting discovery regarding the style of the "update options" menu. It appears that they are hiding this menu by using margin-left: -9999px, and displaying it by overriding ...

What could be the reason for the lack of CSS being applied to elements sharing the same class?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=de ...

Is there a way to automatically close the Foundation topbar menu when a link is selected?

On my single page website, I am utilizing Zurb Foundation's fixed topbar which includes anchor links to different sections of the page. My goal is to have the mobile menu close automatically whenever a link inside it is clicked. As it stands now, whe ...

Reduce the file size of CSS and JS files for Magento

We are facing an issue with minifying CSS and Javascript for our Magento website. Currently, the size of our website is 1.1 MB and we aim to reduce it to 1 MB or even lower if possible. I tried using the "CSS Settings" and "Javascript Settings" functions ...