8

I couldn't find a straightforward way to centre a div in Bootstrap 5. Maybe I am missing something obvious. Google took me to the flex doc. In Bootstrap 4, I could do it by setting col-sm-* and using col-sm-offset-*

Note: I don't want to centre the content in the div. Just need to put whole div in the centre (horizontally). Is setting a margin the only way?

Anupam
  • 14,950
  • 19
  • 67
  • 94
  • @cloned Not sure if it applies to bootstrap 5. I just tried adding `justify-content-center` to the div that I want to center but it didn't do it. I also added the `row` class to it. The div just had an mb set: `
    ` I might be missing the obvious
    – Anupam Sep 20 '21 at 08:08
  • 1
    https://getbootstrap.com/docs/5.1/utilities/flex/#justify-content this is the link for BS5 centering. It's the same as for BS4. – cloned Sep 20 '21 at 08:11
  • @cloned looks like it centers the content _within the div_ but not the div itself. The div still spans the page horizontally. – Anupam Sep 20 '21 at 08:15
  • You have to set a width to the div, otherwise it will span 100% because it's a block element. You should check out hot flexbox works, there is no "magic" way to add a class on a div to center it (and only the div). You can center the div inside a flex-container tough. In the example I linked they centered 3 divs, but it also works with just 1. – cloned Sep 20 '21 at 08:30
  • @cloned you are right - thanks. I noticed that `offset` is just a shortcut and that too puts the content in the centre and adds margins. I found out that `offset` can be used in bootstrap5 (class naming has changed) - I'll use that – Anupam Sep 20 '21 at 11:11

1 Answers1

23

You can use with d-flex align-items-center justify-content-center like below demo:

body{
    height: 100vh;
} 
.container{
    height: 100%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet"/>


<div class="container d-flex align-items-center justify-content-center">
        <div>
                <h1>You Div</h1>
            </div>
    </div>
Tuan Dao
  • 2,647
  • 1
  • 10
  • 20
  • You can also use 'flex-grow-1' class name on container instead of adding height 100% to .container in a stylesheet. – tcanbolat Apr 27 '23 at 03:18