Bootstrap

How do I Center an Image Horizontally in Bootstrap?

While developing any application, images play a vital role in enhancing its visual representation. However, these images must have proper layout and alignment. To align the images, the “img-fluid”, “float-left”, and “float-right” classes can be used. More specifically, to center align the image, the “text-center” and the “mx-auto d-block” classes are utilized.

This write-up will explain how to center an image horizontally in Bootstrap.

Prerequisite: Add an Image

In HTML, add an image by using the “<img>” tag by following the given instructions:

  • >Add a “<div>” element.
  • Within this “<div>” tag, add an image by using the “<img>” element with the “src”, “width”, and “alt” attributes.
  • The “src” sets the image path.
  • The “width” adjusts the image size.
  • The “alt” specifies the alternative text in case the image could not load.

HTML

<div>
<img src="/images/coffee-2390136_1920.jpg" width="500" class="img-responsive" alt="book with coffee">
</div>

Output

How to Center an Image Horizontally in Bootstrap Using “text-center” Class?

The Bootstrap “text-center” class center aligns the images. This class has a predefined CSS “text-align” property with the value “center” that assists in setting the center alignment of an image horizontally.

Example

Assign the “text-center” class to the parent “<div>” element as shown here:

<div class="text-center">

Output

How to Center an Image Horizontally in Bootstrap Using “mx-auto d-block” Class?

The “mx-auto” in combination with the “d-block” class, aligns the image in the center. The “mx-auto” is the CSS “margin” property with the value “auto”, and the “d-block” property is the CSS “display” property with the value “block”.

Example

Let’s implement the “mx-auto” and “d-block” classes to the “<img>” element and see the effect:

<img src="/images/coffee-2336.jpg" width="500" class="mx-auto d-block" alt="book with coffee">

Output

In this way, you can center an image horizontally in Bootstrap.

Conclusion

To center an image horizontally in Bootstrap, first, create an HTML file and add an image to it using the “<img>” tag. Assign it the required attributes, such as “src”, “alt”, “width” and more. Add the “text-center” class to the image’s parent element to adjust the center alignment of the image. The “mx-auto” class, in combination with the “d-block” class, can also be used for this purpose. This write-up has explained how to center an image horizontally using Bootstrap.

About the author

Nadia Bano

I am an enthusiastic and forward-looking software engineer with an aim to explore the global software industry. I love to write articles on advanced-level designing, coding, and testing.