下面是div

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

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


当前回答

基本上,将左右边距设置为自动将导致图像居中对齐。

<div id="over" style="position:absolute; width:100%; height:100%>
<img src="img.png" style="display: block; margin: 0 auto;">
</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图像已经覆盖整个屏幕。即高度: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 >

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

HTML:

<div id="over">
    <img src="img.png">
</div>

CSS:

#over {
  text-align: center;
}

#over img {
  vertical-align: middle;
}

这招对我很管用。

<div class="CenterImage">
         <asp:Image ID="BrandImage" runat="server" />
</div>

注意:在这种情况下,没有与'BrandImage'相关的css类

CSS:

.CenterImage {
    position:absolute; 
    width:100%; 
    height:100%
}

.CenterImage img {
    margin: 0 auto;
    display: block;
}