Center image using text-align center?

Not recommendad:

Another way of doing it would be centering an enclosing paragraph:

<p style="text-align:center"><img src="https://via.placeholder.com/300"></p>

Update:

My answer above is correct if you want to start learning HTML/CSS, but it doesn't follow best practices


That doesn't always work... if it doesn't, try:

img {
    display: block;
    margin: 0 auto;
}

That will not work as the text-align property applies to block containers, not inline elements, and img is an inline element. See the W3C specification.

Use this instead:

img.center {
    display: block;
    margin: 0 auto;
}
<div style="border: 1px solid black;">
<img class="center" src ="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">

</div>

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)

Tags:

Html

Css