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
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
img
in the center of its parent.img
is an inline element, text-center
aligns inline elements in the center of its container should the container be 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>
mx-auto
centers block
elements. In order to so, change display
of the img from inline
to block
with 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>
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>