PUBLISHED ON: AUGUST 10, 2021
How to Align Responsive Image in Center in Bootstrap?
The image is an important component of the webpage. The responsive images adjust themselves according to the size of the viewport.
In this tutorial, we are going to show you how to align the responsive images in the center using Bootstrap 5.
Using text alignment class
The images are made responsive in bootstrap by using the .img-fluid class. The img-fluid has max-width: 100%
and height: auto
which scales up relative to the parent element. To center align the image use .text-center
.
Example: Center align the responsive image using text alignment class
To center align the image, first wrap the <img>
within <div>
element and add the text-center
class to the div element.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" >
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js"></script>
</head>
<body>
<h2 class="text-center">Center align the responsive image in Bootstrap</h2>
<div class="text-center">
<img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/user/profile/picture/iamabhishek1622449489_profile.png" alt="image" class="img-fluid">
</div>
</body>
</html>
Output
Here is the output of the above program.
Using margin utilities
The responsive image can be center-aligned using the margin utilities also. To do so, use the .mx-auto
class. It is used for block-level images.
Example: Center align responsive images using margin utilities
Add .d-block
class along with the .img-fluid
for the block-level responsive image. Here is the code to center align the image using .mx-auto
class.
Conclusion
We have learned to create a responsive image and align it to the center in Bootstrap 5. It can be done using a text-center
class. For block-level images use mx-auto
class.