下面是div

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

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


当前回答

简单。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 id="over" style="position:absolute; width:100%; height:100%>
<img src="img.png" style="display: block; margin: 0 auto;">
</div>

许多答案建议使用margin:0 auto,但只有当你试图使居中的元素不是浮动在左边或右边时,这才有效,即没有设置CSS属性float。为了做到这一点,将display属性应用到table-cell,然后将左右边距应用到auto,这样你的样式将看起来像style="display:table-cell;margin:0 auto;"

一个简单的方法是为div和图像创建单独的样式,然后分别放置它们。比方说,如果我想将图像位置设置为50%,那么我将有如下代码....

在{# 位置:绝对的; 宽度:100%; 高度:100%; } # img { 位置:绝对的; 左:50%; 右:50%; } < div id = " / " > <img src="img.png" id="img"> < / div >

使用自举程序align-items和justification -content。请看下面的例子:

<div class="well" style="align-items:center;justify-content:center;">
    <img src="img_source" height="50px" width="50px"/>
</div>

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

缩放到图像的中心(图像填充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;
    }