There are several methods that can be used to achieve this. Let's explore how it's done in CSS and compare it with the utility classes in Bootstrap.
Assuming we have the following HTML structure:
<div class="parent">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
</div>
Using CSS Flex for the solution:
.parent {
display: flex;
/* Center Horizontally */
justify-content: center;
/* Center Vertically */
align-items: center;
}
Using Bootstrap Flex Utilities for the solution:
<div class="d-flex justify-content-center align-items-center">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
</div>
Using CSS Grid for the solution:
.parent {
display: grid;
/* Center both vertically and horizontally */
place-items: center;
}
Utilizing Bootstrap Grid Utilities for the solution:
Unfortunately, Bootstrap does not have a class for
place-items-center
. Therefore, inline styles can be used.
<div class="d-grid" style="place-items:center">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
</div>
Keep in mind that in order to center an element in the middle of the screen, a height must be defined for the parent element. If a block level element like div
is used, the width is already set to 100%
. However, the height is determined by the content. To achieve centering in the screenshot provided, the parent element should have vh-100
(View Height 100) to expand to full screen height.