Bootstrap is one of the most popular frameworks for building responsive websites that has many features for easy and quick design. One of its interesting capabilities is providing simple methods for vertically centering elements like div vertically and horizontally on the page. In this explanation, we will show with an example how you can center a div vertically on the page.
The first step is to ensure that Bootstrap is properly added to your project. Once this is done, using the features of Bootstrap for vertical centering of elements becomes very simple. A common approach for this task is to use flexbox and Bootstrap classes, which work very well.
In the example below, we have a simple structure using Bootstrap where a div is placed vertically in the center of a page. Thanks to the classes already defined in Bootstrap, it can be achieved by using just a few classes for this purpose.
To create a vertical center, usually the classes .d-flex
, .justify-content-center
, and .align-items-center
are used. These classes utilize the flexbox system to easily align elements both vertically and horizontally within each container.
This work allows you to easily center different divs on the same page in a consistent and visually pleasing layout without needing to use different positions or older methods.
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<title>Vertical Centering with Bootstrap</title>
</head>
<body>
<div class="d-flex justify-content-center align-items-center" style="height: 100vh;">
<div class="p-5 bg-light">Vertical Centering</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
Adding Bootstrap to the project using CDN
<div class="d-flex justify-content-center align-items-center" style="height: 100vh;">
Creating a div that uses flexbox and dedicates the whole page to itself
.justify-content-center
Horizontally centering elements within the div
.align-items-center
Vertically centering elements within the div
style="height: 100vh;"
Setting the height of the div to occupy the full height of the viewport for vertical centering