Skip to content

How to Center Items Horizontally and Vertically using Bootstrap 5

An ongoing meme about CSS and Web Development in general is that centering items such as a div is a lot harder than it needs to be.

I was once asked in an interview how to center text in a div and my answer was “I would look up on google how to do it this week”. I did not get the job. Harsh.

Let’s Center things!

Firstly – I assume you have Bootstrap installed and running on your website.

Say you have this HTML code:

<div class="col border">
    <a class="btn btn-primary">Center Me!</a>
</div>

You will produce this:

Note that I’ve added the border so you can see where the button is sitting.

To center the button inside the div use the following code:

<div class="col border d-flex align-items-center justify-content-center">
    <a class="btn btn-primary">Center Me!</a>
</div>

This will produce:

Which is what we want.

class=”d-flex align-items-center justify-content-center”

The worky bits behind are fairly straight forward. d-flex makes your element use flex-box for positioning.

The align-items-center centers your item horizontally.

And justify-content-center centre’s your item vertically.

You have to use d-flex or it won’t work.

Conclusion

There you have it! How to center items in a div this week! You’re welcome!

Leave a Reply