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:
- Bootstrap 5: How to Create Icon Buttons with Text
- Bootstrap 5: Card Examples
- CSS: Center Text inside a Div with Flexbox
- CSS: Adjust the Gap between Text and Underline
- CSS Flexbox: Make an Element Fill the Remaining Space
You can also check out our CSS category page for the latest tutorials and examples.