3

I have a website and i've centered some images using text-align.

Now in my main content div, i am trying to center an img and it's not working.

<div id="Content" style="width:100%;position:absolute;overflow:auto;top:66px;bottom:200px;">
   <img src="myimg.png" style="text-align: center;" />
</div>

That's all there is to it. Why will all other images center, but not this one?

uSeRnAmEhAhAhAhAhA
  • 2,527
  • 6
  • 39
  • 64

5 Answers5

3

text-align: center needs to be applied to the parent element, in your case, the div:

<div id="Content" style="width:100%;position:absolute;overflow:auto;top:66px;bottom:200px;text-align: center;">
   <img src="myimg.png" />
</div>

Though I strongly discourage the use of inline CSS, so if you have a stylesheet, move it there:

#Content {
    width:100%;
    position:absolute;
    overflow:auto;
    top:66px;
    bottom:200px;
    text-align: center;
}

Another way to do it is the automatically distribute the margins around the element, but this will only work for block-level elements:

#Content > img {
    display: block;
    margin: 0 auto;
}
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • The way you have set the tag up would imply that the content within the image tag would be center aligned. Images have no content, so it does nothing instead. – Thomas Cheney Aug 22 '13 at 15:02
  • I'm applying the style to the `div` element, not the `img` element. The content of the `div` element includes an image. – rink.attendant.6 Aug 22 '13 at 15:04
1

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

<div id="Content" style="width:100%;position:absolute;overflow:auto;top:66px;bottom:200px;text-align: center;">
   <img src="myimg.png" />
</div>
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
1

Text align center should be your div characteristic rather than img.

<div id="Content" style=" text-align: center; width:100%;position:absolute;overflow:auto;top:66px;bottom:200px;">
srijan
  • 1,504
  • 1
  • 13
  • 24
1

You can use auto margins for this:

img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

More reading: w3

or, if you know the width of the image:

img {
  position: absolute;
  left: 50%;
  margin-left: -(half ot the image width)px
}

from here

Community
  • 1
  • 1
robooneus
  • 1,344
  • 8
  • 10
1

Avoid using inline CSS, they are bad to do on websites because search engines take it negatively, always try to use a different stylesheet for the CSS. You can use the code as rink attendant gave.

And text-align can only be used in block containers

Shiva
  • 21
  • 1