Is the property text-align: center;
a good way to center an image using CSS?
img {
text-align: center;
}
There are three methods for centering an element that I can suggest:
Using the text-align
property
.parent {
text-align: center;
}
<div class="parent">
<img src="https://placehold.it/60/60" />
</div>
Using the margin
property
img {
display: block;
margin: 0 auto;
}
<img src="https://placehold.it/60/60" />
Using the position
property
img {
display: block;
position: relative;
left: -50%;
}
.parent {
position: absolute;
left: 50%;
}
<div class="parent">
<img src="https://placehold.it/60/60" />
</div>
The first and second methods only work if the parent is at least as wide as the image. When the image is wider than its parent, the image will not stay centered!!!
But: The third method is a good way for that!
Here's an example:
img {
display: block;
position: relative;
left: -50%;
}
.parent {
position: absolute;
left: 50%;
}
<div class="parent">
<img src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/img_01.jpg" />
</div>
Use this to your img
CSS:
img {
margin-right: auto;
margin-left: auto;
}
The simplest solution I found was to add this to my img-element:
style="display:block;margin:auto;"
It seems I don't need to add "0" before the "auto" as suggested by others. Maybe that is the proper way, but it works well enough for my purposes without the "0" as well. At least on latest Firefox, Chrome, and Edge.
I came across this post, and it worked for me:
img {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div style="border: 1px solid black; position:relative; min-height: 200px">
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">
</div>
(Vertical and horizontal alignment)
Sometimes we directly add the content and images on the WordPress administrator inside the pages. When we insert the images inside the content and want to align that center. Code is displayed as:
**<p><img src="https://abcxyz.com/demo/wp-content/uploads/2018/04/1.jpg" alt=""></p>**
In that case you can add CSS content like this:
article p img{
margin: 0 auto;
display: block;
text-align: center;
float: none;
}
On the container holding image you can use a CSS 3 Flexbox to perfectly center the image inside, both vertically and horizontally.
Let's assume you have <div class="container"> as the image holder:
Then as CSS you have to use:
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
And this will make all your content inside this div perfectly centered.