简体   繁体   中英

how to align an image to the center of the div?

I am trying to align an image in a div to center. I have tried the following but its not working. Please tell me how to fix this . thanks in advance.

<div class="erabox"><img src="indicator2.gif" alt="1910 to 1919" width="229" height="38" /></div>
<div class="erabox" style="text-align:center"><img src="indicator2.gif" alt="1910 to 1919" width="229" height="38" /></div>

只需要div标签中的style="text-align:center"

Try with the following CSS code. It makes your <img> aligned center horizontally and aligned middle vertically.

.erabox{
    width:200px;
    height:200px;
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}

Just use margin auto:

  .erabox img {
    display: block;
    margin: auto;
  }

DEMO: http://jsbin.com/apiwox/edit#html,live

Try below code in CSS. it will work for sure align="absmiddle"

CSS

.erabox{
    position:relative;
}

.erabox img{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-19px; /* Half of images height */
    margin-left:-115px; /* Half of images width */
}

If .erabox div's width and height are fixed or at least it's height and width are always surely greater than image's you can use image as a background

HTML

<div class="erabox"></div>

CSS

.erabox{
    background:url("indicator2.gif") no-repeat;
    background-position:50% 50%;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM