下面是div

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

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


当前回答

我仍然有一些问题与其他解决方案在这里提出。最后,这对我来说是最好的:

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

css3:

.child {
 display: block;
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 -webkit-transform: translate(-50%, -50%); /* Safari and Chrome */
 -moz-transform: translate(-50%, -50%); /* Firefox */
 -ms-transform: translate(-50%, -50%); /* IE 9 */
 -o-transform: translate(-50%, -50%); /* Opera */
 // I suppose you may like those too:
 // max-width: 80%;
 // max-height: 80%;
}

您可以在本页阅读更多关于这种方法的信息。

其他回答

在我看来,您还希望图像在容器中垂直居中。(我没有看到任何答案提供了这一点)

工作小提琴:

纯CSS解决方案 不中断文档流(没有浮动或绝对定位) 跨浏览器兼容性(甚至包括IE6) 完全响应。

HTML

<div id="over">
    <span class="Centerer"></span>
    <img class="Centered" src="http://th07.deviantart.net/fs71/200H/f/2013/236/d/b/bw_avlonas_a5_beach_isles_wallpaper_image_by_lemnosexplorer-d6jh3i7.jpg" />
</div>

CSS

*
{
    padding: 0;
    margin: 0;
}
#over
{
    position:absolute;
    width:100%;
    height:100%;
    text-align: center; /*handles the horizontal centering*/
}
/*handles the vertical centering*/
.Centerer
{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.Centered
{
    display: inline-block;
    vertical-align: middle;
}

注意:此解决方案适用于在任何元素中对齐任何元素。 对于IE7,当在块元素上应用.居中类时,你将不得不使用另一个技巧来让内联块工作。(这是因为IE6/IE7不能很好地使用内联块对块元素)

我仍然有一些问题与其他解决方案在这里提出。最后,这对我来说是最好的:

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

css3:

.child {
 display: block;
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 -webkit-transform: translate(-50%, -50%); /* Safari and Chrome */
 -moz-transform: translate(-50%, -50%); /* Firefox */
 -ms-transform: translate(-50%, -50%); /* IE 9 */
 -o-transform: translate(-50%, -50%); /* Opera */
 // I suppose you may like those too:
 // max-width: 80%;
 // max-height: 80%;
}

您可以在本页阅读更多关于这种方法的信息。

#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;
}

这招对我很管用:

#image-id {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    width: auto;
    margin: 0 auto;
}

我向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;
}