下面是div

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

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


当前回答

我向CSS添加了更多的属性。像这样:

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

其他回答

标记的答案将不会垂直对齐图像。适合现代浏览器的解决方案是flexbox。flex容器可以配置为水平和垂直对齐其项。

<div id="over" style="position:absolute; width:100%; height:100%; display: flex; align-items: center; justify-content: center;">
    <img src="img.png">
</div>

这为我工作,当你必须居中对齐图像和你的父div图像已经覆盖整个屏幕。即高度:100%,宽度:100%

#img{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}

这也可以使用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 >

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

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

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

  
#over {position:relative; text-align:center; 
       width:100%; height:100%; background:#CCC;}

#over img{
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}