0

I need to center an image, at least horizontally, without using tables and workable on at least Internet Explorer 8. (Internet Explorer 7 too if possible).

I need a solution similar to an earlier asked question on Stack Overflow, Center an image inside a div?, but doing it using tables, which is not acceptable solution here.

I tried a Fiddle with "margin:0px auto", which work for all other elements, but it is not working for an image. Quick code is as follows.

HTML

<div class="outer">
    <img src="https://m.ak.fbcdn.net/profile.ak/hprofile-ak-ash4/195658_100001734379625_1121483775_q.jpg" width="100" height="100" />
</div>​

CSS

.outer{
    width:300px;
    border:1px #000 solid;
    padding:5px;
}.outer img{
    border:1px #F00 solid;
    margin:0 auto;
}

Is there any pure CSS solution, if possible but not necessarily, applicable for Internet Explorer 7 too?

Community
  • 1
  • 1
Kapil Sharma
  • 10,135
  • 8
  • 37
  • 66

4 Answers4

2

Add text-align:center; into .outer class.

.outer{
    width:300px;
    border:1px #000 solid;
    padding:5px;
    text-align:center;
}
PepeDeLew
  • 346
  • 4
  • 15
2

If you want to center both vertically and horizontally:

.outer{
    width:300px;
    height: 300px;
    border:1px #000 solid;
    padding:5px;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.outer img{
    border:1px #F00 solid;
}

http://jsfiddle.net/M7LJx/1/

Note display: table-cell will not work on IE7 though.

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
2

Just replace the CSS code:

.outer{
    width:300px;
    border:1px #000 solid;
    padding:5px;
    margin:0 auto;
    text-align: center;
}
.outer img {
    border:1px #F00 solid;
}

It works in all browsers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SpritsDracula
  • 1,080
  • 9
  • 16
0

If your img must be display:block, then you must use margin:0 auto; because, text-align:center; will not work for block element.

But, if your img is display:inline; (or not set, so default is inline), then text-align will work.

marinbgd
  • 739
  • 13
  • 28