简体   繁体   English

如何将图像与div的中心对齐?

[英]how to align an image to the center of the div?

I am trying to align an image in a div to center. 我试图将div中的图像对齐到中心。 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. 尝试使用以下CSS代码。 It makes your <img> aligned center horizontally and aligned middle vertically. 它使您的<img>水平对齐中心并垂直对齐。

.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 演示: http//jsbin.com/apiwox/edit#html,live

Try below code in CSS. 在CSS中尝试下面的代码。 it will work for sure align="absmiddle" 它肯定会对齐=“absmiddle”

CSS 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 如果.erabox div的宽度和高度是固定的,或者至少它的高度和宽度总是肯定大于图像,你可以使用图像作为背景

HTML HTML

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

CSS CSS

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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