I am new to Bootstrap 4, earlier in Bootstrap 3 we use class "center-block", now I am not able to find this in new version.
Asked
Active
Viewed 2.1k times
-1
-
Read https://getbootstrap.com/docs/4.0/migration/#utilities – Ron van der Heijden Mar 08 '18 at 13:28
3 Answers
9
Center an inline element has nothing to do with Bootstrap actually.
Center the image using text-align
An image is an inline element and can be aligned using text-align
.
Text will flow around the image, since it is an inline element.
Normally:
<div style="text-align: center;">
<img src="http://placehold.it/200x200" />
</div>
The Bootstrap way:
<div class="text-center">
<img src="http://placehold.it/200x200" />
</div>
Center the image using margin
You can change the display of the image to a block element and use margin to center the block.
Text will be pushed above and under the image since we change the display to block
.
<div>
<img src="http://placehold.it/200x200" style="display: block;margin: auto;" />
</div>
The Bootstrap way:
<div>
<img src="http://placehold.it/200x200" class="mx-auto d-block" />
</div>
Full example
.my-text-center {
text-align: center;
}
.my-block-center {
display: block;
margin: auto;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="my-text-center">
<img src="http://placehold.it/200x200" />
</div>
<div class="text-center">
<img src="http://placehold.it/200x200" />
</div>
<div>
<img src="http://placehold.it/200x200" class="my-block-center" />
</div>
<div>
<img src="http://placehold.it/200x200" class="mx-auto d-block" />
</div>

Ron van der Heijden
- 14,803
- 7
- 58
- 82
8
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>
More info in this link

El0din
- 3,208
- 3
- 20
- 31
-
1
-
Worked charmly for my case too. But I think it lacks a bit of an explanation. How that works ? – hephestos Sep 12 '19 at 20:53
-
1Image 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. In the link is the original answer – El0din Sep 12 '19 at 21:24
-
-1
Try using this code.
html:
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12 centered">
<img alt="Bootstrap Image Preview" src="http://lorempixel.com/140/140/" />
</div>
</div>
</div>
</div>
</div>
css:
centerd{
text-align: center;
}

M. van Laar
- 42
- 5