Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

html - 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.

question from:https://stackoverflow.com/questions/7123599/how-to-display-image-in-the-center-of-a-div

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...