Center image using text-align center?

Web_Designer picture Web_Designer · Aug 14, 2011 · Viewed 1.3M times · Source

Is the property text-align: center; a good way to center an image using CSS?

img {
    text-align: center;
}

Answer

Mrchief picture Mrchief · Aug 14, 2011

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>