下面是div

<div id="over" style="position:absolute; width:100%; height:100%>
 <img src="img.png">
</div>

如何对齐图像,使其位于div的中间和中心?


当前回答

这将是一种更简单的方法

#over > img{
    display: block;
    margin:0 auto; 
}

其他回答

你可以通过使用display:flex CSS属性轻松做到这一点:

#over {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

  

这将是一种更简单的方法

#over > img{
    display: block;
    margin:0 auto; 
}

使用定位。下面的方法对我很有效……

缩放到图像的中心(图像填充div):

div{
    display:block;
    overflow:hidden;
    width: 70px; 
    height: 70px;  
    position: relative;
}
div img{
    min-width: 70px; 
    min-height: 70px;
    max-width: 250%; 
    max-height: 250%;    
    top: -50%;
    left: -50%;
    bottom: -50%;
    right: -50%;
    position: absolute;
}

没有缩放到图像的中心(图像不填充div):

   div{
        display:block;
        overflow:hidden;
        width: 100px; 
        height: 100px;  
        position: relative;
    }
    div img{
        width: 70px; 
        height: 70px; 
        top: 50%;
        left: 50%;
        bottom: 50%;
        right: 50%;
        position: absolute;
    }

简单。2018. FlexBox。检查浏览器支持-我可以使用 最小的解决方案:

div#over { 
   display: flex; 
   justify-content: center; 
   align-items: center; 
}

要获得尽可能广泛的浏览器支持:

div#over { 
   display: -webkit-flex;
   display: -ms-flex; 
   display: flex; 
   justify-content: center; 
   -ms-align-items: center; 
   align-items: center; 
}
    <div>
    <p style="text-align:center; margin-top:0px; margin-bottom:0px; padding:0px;">
    <img src="image.jpg" alt="image"/>
    </p>    
    </div>