Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I center an image in Bootstrap?

I am struggling to center an image using only Bootstrap's CSS-classes. I already tried several things. One was adding Bootstrap CSS-class mx-auto to the img element, but it does nothing.

Help is appreciated.

<div class="container">     <div class="row">         <div class="col-4 mx-auto">             <img class=""...> <!-- center this image within the column -->              <form...>              <p...>             <p...>             <p...>                         </div>     </div> </div> 
like image 907
Daniel Avatar asked Apr 05 '17 09:04

Daniel


People also ask

How do I center an image in Bootstrap 5?

You can center the image by adding the . text-center class to the image's parent element.

How do I center an image in a div using Bootstrap?

Answer: Use the center-block Classcenter-block on it, along with the . img-responsive class in Bootstrap 3.

How do I center align an image in Bootstrap 4?

By default, images are display:inline . If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work. Save this answer.

How do I center an image horizontally in Bootstrap?

justify-content-center classes to the parent element of the image to center it horizontally. Add . d-flex . align-items-center-center classes to the parent element of the image to center it vertically.


2 Answers

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div class="container">     <div class="row">         <div class="col-4">             <img class="mx-auto d-block" src="...">           </div>     </div> </div> 

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="container">     <div class="row">         <div class="col-4">           <div class="text-center">             <img src="...">            </div>              </div>     </div> </div> 

I made a fiddle showing both ways. They are documented here as well.

like image 91
tmg Avatar answered Sep 22 '22 16:09

tmg


Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">     <div class="col-4 mx-auto text-center">         <img src="..">     </div> </div> 

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">   <div class="col-4">     <img class="mx-auto d-block" src="..">   </div> </div> 

Demo: http://codeply.com/go/iakGGLdB8s

like image 20
Zim Avatar answered Sep 22 '22 16:09

Zim