Joper Joper - 6 months ago 11
CSS Question

How to display image in the center of a div

I have div with ajax-loader gif image

<div id="mydiv" style="height: 400px; text-align: center;">
<img src="/Content/ajax-loader.gif" class="ajax-loader"/>
</div>


.ajax-loader
{
/*hidden from IE 5-6 */
margin-top: 0; /* to clean up, just in case IE later supports valign! */
vertical-align: middle;
margin-top: expression(( 150 - this.height ) / 2);
}


But could not get it displayed in the center (both vertically and horizontally). Need help with that.

Answer

The following assumes that the width and height of the image is known:

#mydiv {
  height: 400px;
  position: relative;
  background-color: gray; /* for demonstration */
}
.ajax-loader {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -32px; /* -1 * image width / 2 */
  margin-top: -32px; /* -1 * image height / 2 */
}
<div id="mydiv">
  <img src="http://dummyimage.com/64x64/000/fff.gif&text=LOADING" class="ajax-loader">
</div>

UPDATE: in modern browsers margin: auto will produce the desired result withing knowing the width/height of the image:

#mydiv {
  height: 400px;
  position: relative;
  background-color: gray; /* for demonstration */
}
.ajax-loader {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto; /* presto! */
}
<div id="mydiv">
  <img src="http://dummyimage.com/64x64/000/fff.gif&text=LOADING" class="ajax-loader">
</div>

Comments