Bootstrap 5: Vertically Center an Element inside a Div

Updated: March 3, 2023 By: Pennywise Post a comment

The examples below show you how to vertically center an element that locates inside a div element. We are going to use Bootstrap 5 and its d-flex class to make the parent div become a flexbox container.

Example 1: Vertically Center

Screenshot:

The code:

<html lang="en">
  <head>
    <!-- Bootstrap 5 -->
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <title>Kindacode.com</title>
  </head>

  <body>
    <div
      class="bg-success d-flex align-items-center"
      style="width: 500px; height: 400px"
    >
      <div class="bg-warning" style="width: 150; height: 100"></div>
    </div>
  </body>
</html>

Example 2: Both Vertically And Horizontally Center

Screenshot:

The code:

<html lang="en">
  <head>
    <!-- Bootstrap 5 -->
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <title>Kindacode.com</title>
  </head>

  <body>
    <div
      class="bg-info d-flex align-items-center justify-content-center"
      style="width: 500px; height: 400px"
    >
      <div class="bg-warning" style="width: 150; height: 100"></div>
    </div>
  </body>
</html>

If you replace the child div by a text, the result will be the same:

The code:

 <div
      class="bg-info d-flex align-items-center justify-content-center"
      style="width: 500px; height: 400px"
    >
      <h1>KindaCode.com</h1>
    </div>

Final Words

We’ve gone through a few examples of vertical alignment with Bootstrap 5. If you’d like to explore more new and interesting stuff of modern frontend development, take a look at the following articles:

You can also check out our CSS category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles