下面是div
<div id="over" style="position:absolute; width:100%; height:100%>
<img src="img.png">
</div>
如何对齐图像,使其位于div的中间和中心?
下面是div
<div id="over" style="position:absolute; width:100%; height:100%>
<img src="img.png">
</div>
如何对齐图像,使其位于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;
}
将img设置为display:inline-block,同时将高级div设置为text-align:center也可以完成这项工作
编辑:对于那些正在玩display:inline-block >>>的人,不要忘记例如,两个div像
<div>Div1 content</div>NOSPACEHERE<div>Div2 content</div>
它们之间真的没有空格(如图所示)。
只是基本避免这些(内联块固有)之间的差距。这些空白可以在我现在写的每两个字之间看到!:-)所以…希望这能对你们有所帮助。
这将是一种更简单的方法
#over > img{
display: block;
margin:0 auto;
}
我仍然有一些问题与其他解决方案在这里提出。最后,这对我来说是最好的:
<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%;
}
您可以在本页阅读更多关于这种方法的信息。
使用定位。下面的方法对我很有效……
缩放到图像的中心(图像填充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;
}