下面是div

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

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


当前回答

这也可以使用Flexbox布局完成:

静态的大小 .parent { 显示:flex; 身高:300 px;/*或者*/ background - color: # 000; } .child { 宽度:100 px;/*或者*/ 身高:100 px;/*或者*/ 保证金:汽车;/ *魔法!* / } < div class = "父" > <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/> < / div >

动态规模 Html, body { 宽度:100%; 高度:100%; 显示:flex; background - color: # 999; } * { 保证金:0; 填充:0; } .parent { 保证金:汽车; background - color: # 000; 显示:flex; 高度:80%; 宽度:80%; } .child { 保证金:汽车;/ *魔法!* / max-width: 100%; max-height: 100%; } < div class = "父" > <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/> < / div >

我在这篇文章中找到了一个例子,它很好地解释了如何使用布局。

其他回答

水平放置

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

另一种方法:

#over img {
    display: inline-block;
    text-align: center;
}

只需要放置:

   #over img {

           vertical-align: middle;
        }
#over {
    display: table-cell; 
    vertical-align: middle; 
    text-align: center;
    height: 100px;
}

根据您的需要修改高度值。

只需设置父div css属性“text-align:center;”

 <div style="text-align:center; width:100%">
        <img src="img.png"> 
 </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;
    }
<div style="display:table-cell; vertical-align:middle; text-align:center">
<img src="img.png">
</div>