How can I center an image in Bootstrap?
The Bootstrap class .center-block
works well.
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.
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
3 ways to align img
in the center of its parent.
1.
img
is an inline element, .text-center
aligns inline elements in center if the element its used on, is a block
element.
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>
<div class="container mt-5">
<div class="row">
<div class="col text-center">
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">
</div>
</div>
</div>
2.
.mx-auto
centers block
elements. In order to so, change the display
of the img from inline
to block
using the .d-block
class.
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>
<div class="container mt-5">
<div class="row">
<div class="col">
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">
</div>
</div>
</div>
3.
Use .d-flex
and .justify-content-center
on its parent.
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>
<div class="container mt-5">
<div class="row">
<div class="col d-flex justify-content-center">
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">
</div>
</div>
</div>