396

I am trying to center my Container in the middle of the page using Bootstrap 4. I have been unsuccessful thus far. Any help would be appreciated.

I have built it at Codepen.io so you guys can play with it and let me know what works as I am about 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>
Temani Afif
  • 180,975
  • 14
  • 166
  • 216
canaan seaton
  • 5,684
  • 3
  • 14
  • 20

15 Answers15

828

Important! Vertical center is relative to the height of the parent

If the parent of the element you're trying to center has no defined height, none of the vertical centering solutions will work!

Now, onto vertical centering...

Bootstrap 5 Beta (Updated 2021)

Bootstrap 5 is still flexbox based so vertical centering works the same way as Bootstrap 4. For example align-items-center and justify-content-center can used on the flexbox parent (row or d-flex). https://codeply.com/p/0VM5MJ7Had

Bootstrap 4

You can use the new flexbox & size utilities to make the container full-height and display: flex. These options don't require extra CSS (except that the height of the container (ie:html,body) must be 100%).

Option 1 align-self-center on flexbox child

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

https://codeply.com/go/fFqaDe5Oey

Option 2 align-items-center on flexbox parent (.row is display:flex; flex-direction:row)

<div class="container h-100">
    <div class="row align-items-center h-100">
        <div class="col-6 mx-auto">
            <div class="jumbotron">
                I'm vertically centered
            </div>
        </div>
    </div>
</div>

enter image description here

https://codeply.com/go/BumdFnmLuk

Option 3 justify-content-center on flexbox parent (.card is display:flex;flex-direction:column)

<div class="container h-100">
    <div class="row align-items-center h-100">
        <div class="col-6 mx-auto">
            <div class="card h-100 border-primary justify-content-center">
                <div>
                    ...card content...
                </div>
            </div>
        </div>
    </div>
</div>

https://codeply.com/go/3gySSEe7nd


More on Bootstrap 4 Vertical Centering

Now that Bootstrap 4 offers flexbox and other utilities, there are many approaches to vertical alignment. http://www.codeply.com/go/WG15ZWC4lf

1 - Vertical Center Using Auto Margins:

Another way to vertically center is to use my-auto. This will center the element within it's container. For example, h-100 makes the row full height, and my-auto will vertically center 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>

Vertical Center Using Auto Margins Demo

my-auto represents margins on the vertical y-axis and is equivalent to:

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

2 - Vertical Center with Flexbox:

vertical center grid columns

Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

       <div class="row">
           <div class="col-6 align-self-center">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

or, use align-items-center on the entire .row to vertically center align all col-* in the row...

       <div class="row align-items-center">
           <div class="col-6">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

Vertical Center Different Height Columns Demo

See this Q/A to center, but maintain equal height


3 - Vertical Center Using Display Utils:

Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

<div class="row h-50">
    <div class="col-sm-12 h-100 d-table">
        <div class="card card-block d-table-cell align-middle">
            I am centered vertically
        </div>
    </div>
</div>

Vertical Center Using Display Utils Demo

More examples
Vertical center image in <div>
Vertical center .row in .container
Vertical center and bottom in <div>
Vertical center child inside parent
Vertical center full screen jumbotron


Important! Did I mention height?

Remember vertical centering is relative to the height of the parent element. If you want to center on the entire page, in most cases, this should be your CSS...

body,html {
  height: 100%;
}

Or use min-height: 100vh (min-vh-100 in Bootstrap 4.1+) on the parent/container. If you want to center a child element inside the parent. The parent must have a defined height.

Also see:
Vertical alignment in bootstrap 4
Bootstrap 4 Center Vertical and Horizontal Alignment

Zim
  • 296,800
  • 77
  • 616
  • 554
  • 1
    When using above on a page with a navbar I'm getting a scrollbar. I think it's adding 100% height below the navbar and centering across it. How can I fix that? – newdimension Dec 10 '17 at 06:50
  • I am trying to align multiple rows to centre with flex box. I want to align all buttons in centre. https://www.codeply.com/go/5abdqC33cU – Coder Mar 15 '19 at 17:09
  • 1
    I prepared a codepen currently showing 3 ways of centering based on the ways shown here: https://codepen.io/yigith/pen/oNjmGEL – KodFun May 21 '20 at 19:56
  • Option 1 only worked for me when `
    ` was changed to `
    `
    – half of a glazier Nov 06 '20 at 11:57
  • That's correct since `h-100` is 100% of its parent container while `vh-100` is height of the viewport. At the time the question was asked,`vh-100` didn't exist in Bootstrap. – Zim Nov 06 '20 at 12:03
34

you can vertically align your container by making the parent container flex and adding align-items:center:

body {
  display:flex;
  align-items:center;
}

Updated Pen

Pete
  • 51,385
  • 23
  • 99
  • 140
  • 1
    ohhh lol, I missed the link in the description... you also added `html, body {height:100%}` ... adding that made it work! Thanks! – canaan seaton Feb 15 '17 at 15:00
  • 3
    your answer doesnt solve the problem in the asked way (using bootstrap) – Alexey Nikonov Jun 13 '19 at 12:42
  • 1
    im totaly not agree with you, you propose to workaround despite of the question was about how do it with Bootstrap classes. – Alexey Nikonov Jun 14 '19 at 09:58
  • 1
    @AlexNikonov no where in the OP question does it say they are limited to using bootstrap only - this is an alternative for other people who may land on this page looking to vertically align things without the use of bootstrap classes. Just move along - there are plenty of other answers here for you to use. I don't see why you're getting hung up about this - this is a forum for all ideas that will help - not just single minded answers. It is users like you spoiling this site by downvoting answers that offer a solution to the problem but just because you don't like it – Pete Jun 14 '19 at 10:32
  • @AlexNikonov also if you read the original unedited post (when I added my answer), you will also see OP was trying to centre without using bootstrap classes so at the time of answering, this was correct – Pete Jun 14 '19 at 10:39
  • 1
    Or with BS4:
    some text
    – MingalevME Oct 02 '19 at 11:55
  • Didn't work for me under Bootstrap 5. CSS has too many interactions with itself. – David Spector Apr 14 '21 at 21:50
34

Following bootstrap 4 classes helped me solve this

<div class="col text-center justify-content-center align-self-center">
    <img width=3rem src=".." alt="...">
</div>
Manoj
  • 608
  • 6
  • 7
16

Because none of the above worked for me, I am adding another answer.

Goal: To vertically and horizontally align a div on a page using bootstrap 4 flexbox classes.

Step 1: Set your outermost div to a height of 100vh. This sets the height to 100% of the Veiwport Height. If you don't do this, nothing else will work. Setting it to a height of 100% is only relative to the parent, so if the parent is not the full height of the viewport, nothing will work. In the example below, I set the Body to 100vh.

Step 2: Set the container div to be the flexbox container with the d-flex class.

Step 3: Center div horizontally with the justify-content-center class.

Step 4: Center div vertically with the align-items-center

Step 5: Run page, view your vertically and horizontally centered div.

Note that there is no special class that needs to be set 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>
Greg Gum
  • 25,941
  • 27
  • 127
  • 194
11
.jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}
Nate Beers
  • 1,277
  • 1
  • 12
  • 21
11

I did it this way with Bootstrap 4.3.1:

<div class="d-flex vh-100">
  <div class="d-flex w-100 justify-content-center align-self-center">
    I'm in the middle
  </div>
</div>
webjay
  • 4,668
  • 8
  • 37
  • 53
7
<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>Heading</h3>
     <p>Some text.</p>
   </div>
</div>

This line is where the magic happens <div class="col-md-6 my-auto">, the my-auto will center the content of the column. This works great with situations like the code sample above where you might have a variable sized image and need to have the text in the column to the right line up with it.

Rob
  • 5,576
  • 4
  • 39
  • 46
5

I've tried all the answers herefrom, but found out here is the difference between h-100 and vh-100 Here is my solution:

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

Alexey Nikonov
  • 2,164
  • 1
  • 19
  • 33
4

In Bootstrap 4 (beta), use align-middle. Refer to Bootstrap 4 Documentation on Vertical alignment:

Change the alignment of elements with the vertical-alignment utilities. Please note that vertical-align only affects inline, inline-block, inline-table, and table cell elements.

Choose from .align-baseline, .align-top, .align-middle, .align-bottom, .align-text-bottom, and .align-text-top as needed.

vallismortis
  • 6,155
  • 12
  • 65
  • 81
4
<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">Our Offer</span>
                <h2 class="section-title">Today’s Special </h2>
                <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly.</p>
            </div>
        </div>

enter image description here

Tariqul_Islam
  • 399
  • 3
  • 5
3
<!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/4.2.1/js/bootstrap.min.js"></script>
</head>
<body>  
<div class="container">
    <div class="row align-items-center justify-content-center" style="height:100vh;">     
         <div>Center Div Here</div>
    </div>
</div>
</body>
</html>
Anu
  • 121
  • 2
  • 8
2

Vertical align Using this bootstrap 4 classes:

Method1:

parent: d-table

AND

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

eg:

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

and if you want parent be circle:

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

which two custom css classes are as follow:

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

Final usage can be like for example:

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

Method2: You can use following:

parent: h-100 d-table mx-auto

AND

child: d-table-cell align-middle

Method3:

You can use following:

parent: d-flext align-items-center

also if you want content be center horisontally too:

parent: d-flext align-items-center justify-content-center

0

use .my-auto (bootsrap4) css class on yor div

Preshan Pradeepa
  • 553
  • 13
  • 26
0

Place your content within a flexbox container that is 100% high i.e h-100. Then justify the content centrally by using justify-content-center class.

<section class="container h-100 d-flex justify-content-center">
    <div class="jumbotron my-auto">
        <h1 class="display-3">Hello, Malawi!</h1>
    </div>
</section>
Mwiza
  • 4,494
  • 2
  • 33
  • 30
-2

In Bootstrap 4.1.3:

This worked for me when I was trying to center a bootstrap badge inside of a container > row > column next to a h1 title.

What did work was some simple css:

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

or

<span class="badge badge-pill" style="vertical-align: 50%;">My Badge</span>
phyatt
  • 16,890
  • 3
  • 51
  • 70