下面是div

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

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


当前回答

试试下面的代码:

<div class="outer">
    <img src="image.png"/>
</div>

和CSS:

.outer{
  text-align: center;
}
.outer img{
  display: inline-block;
}

其他回答

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

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

HTML:

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

CSS:

#over {
  text-align: center;
}

#over img {
  vertical-align: middle;
}

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

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

这应该有用。

测试要点:要运行代码段,请单击左键运行代码段,然后单击右链接完整页

#渐变{ 位置:固定;z - index: 10; 上图:0;右:0;底:0;左:0; 透明度:0.8;背景:黑色; 宽度:100%;高度:100%; text-align:中心; } .faders{显示:inline-block;高度:100%;vertical-align:中间;} .faderi{显示:inline-block; vertical-align:中间;} < div id = "渐变" > < span class = "投篮" > < / span > <img class="faderi" src="https://i.stack.imgur.com/qHF2K.png" /> < / div >

img.centered {
   display: block;
   margin: auto auto;
}