How To Center a div Horizontally in Bootstrap 4 & 5

How To Center a div Horizontally in Bootstrap 4 & 5

It is very common in web design layouts to horizontally center a column in a row or container. But how do you do that using Bootstrap classes? Below are some different ways you can achieve this effect.

Update: These methods work for both Bootstrap 5 and Bootstrap 4. Here is a codepen demo for just Bootstrap 5 of these horizontally centered columns options.

Option 1 – Bootstrap Offset

You can use Bootstrap offset classes to horizontally shift columns left or right. This is helpful when you want one column to have a max width but center it in a row.

Tired of WordPress? Try HubSpot CMS

  <div class="row">
    <div class="col-md-8 offset-md-2">
      <h3>Look! I am Centered Horizontally</h3>
    </div>
  </div>

Option 2 – Margin Auto

This example sets the maximum width on medium breakpoints and up to be 8 columns wide. Then I added a utility class of .mx-auto that sets the margin left and right to auto centering it horizontally inside the .row container.

  <div class="row">
    <div class="col-md-8 mx-auto">
      <h3>Me Too!</h3>
    </div>
  </div>

Option 3 – Bootstrap Width Utility

In this example, I am using Bootstrap’s width utility class of .w-50 to make the div 50% wide all the time. Then I added a utility class of .mx-auto that sets the margin left and right to auto centering it horizontally inside the .row container.

  <div class="row">
    <div class="w-50 mx-auto">
      <h3>Me Three!</h3>
    </div>
  </div>

Option 4 – Use Flexbox Classes

If you have multiple items you want to center you could try using a combination of flexbox classes. Here is a flexbox cheat sheet showing how they work.

Download free digital marketing guides & templates

  <div class="d-flex justify-content-center flex-nowrap">
    <div class="bg-secondary text-white mx-2 p-2">
      item 1
    </div>
     <div class="bg-secondary text-white mx-2 p-2">
      item 2
    </div>
     <div class="bg-secondary text-white mx-2 p-2">
      item 3
    </div>
  </div>

Conclusion

As in most cases in web development, there is more than one way to achieve the same result. Choosing the right approach for your project depends on what you think is easiest to remember and maintain. Personally, I like Option 1 because it allows you to horizontally center the column on large screens and then go full width on mobile.

View Codepen Demo



Written by: Jake Lett
I share digital marketing tips and HubSpot tutorials to help marketers and business owners grow their business.

Tags: , ,