Advertisement
Advertisement


Center image using text-align center?


Question

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

img {
    text-align: center;
}
2013/08/15
1
521
8/15/2013 1:44:50 AM

Accepted Answer

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>

2019/09/12
1104
9/12/2019 9:44:19 PM

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

img {
    display: block;
    margin: 0 auto;
}
2011/08/14

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)


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

<p style="text-align:center; border:1px solid black"><img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a"></p>

2019/09/12

You can do:

<center><img src="..." /></center>

2015/08/10

Actually, the only problem with your code is that the text-align attribute applies to text (yes, images count as text) inside of the tag. You would want to put a span tag around the image and set its style to text-align: center, as so:

span.centerImage {
     text-align: center;
}
<span class="centerImage"><img src="http://placehold.it/60/60" /></span>

The image will be centered. In response to your question, it is the easiest and most foolproof way to center images, as long as you remember to apply the rule to the image's containing span (or div).

2017/05/22

Source: https://stackoverflow.com/questions/7055393
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]