Why does "text-align:center" work for "div" but not for "img"?

846 Views Asked by At

Here is an example:

p, span, div,img {
    text-align: center;
}
<p>Para</p>
<span>Span</span>
<div>Div</div>
<img src="https://www.google.com/images/nav_logo195.png" />
<div><img src="https://www.google.com/images/nav_logo195.png" /></div>

I found apply text-align: center on img directly doesn't work.

Does this mean it has to be wrapped in an empty div when a centered image is needed?

Is there a better way to do this?

4

There are 4 best solutions below

0
On

text-align: center centers horizontally inline content of the container it is applied to. So yes, to center image (inline layout) inside container (block layout), you should apply this css to container, not image.

3
On

text-align aligns the text (and other inline) content inside the element to which it is applied.

There is no content inside an image.

You can either:

  • Make the image display as a block and then use auto margins
  • Put it inside any block element (it doesn't have to be a div, but that's usually the most sensible choice if you are just centring it) and set text-align on that container.
5
On

Instead of using the text-align on img tag, use it on div

p, span, div,img {
    text-align: center;
}
#testimg {
  width:100%;
  position:absolute;
  overflow:auto;
  top:50px;
  height: 100%;
  }
<div id="testimg">
   <img src="https://www.google.com/images/nav_logo195.png" />
</div>

0
On

If you want to center an img use:

img {
    display: block;
    margin 0 auto;
}