下面是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的中间和中心?
当前回答
Daaawx的答案是可行的,但我认为如果我们消除内联css会更干净。
身体{ 保证金:0; } #over img { margin-left:汽车; margin-right:汽车; 显示:块; } div.example { 位置:绝对的; 宽度:100%; 高度:100%; } <div class="example" id="over"> < img src = " http://www.garcard.com/images/garcard_symbol.png " > < / div >
其他回答
#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;
}
使用定位。下面的方法对我很有效……
缩放到图像的中心(图像填充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;
}
简单。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;
}
标记的答案将不会垂直对齐图像。适合现代浏览器的解决方案是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>
你可以看看这个解决方案:
水平和垂直居中一个盒子中的图像
<style type="text/css">
.wraptocenter {
display: table-cell;
text-align: center;
vertical-align: middle;
width: ...;
height: ...;
}
.wraptocenter * {
vertical-align: middle;
}
.wraptocenter {
display: block;
}
.wraptocenter span {
display: inline-block;
height: 100%;
width: 1px;
}
</style>
<!--[if lt IE 8]-->
<style>
.wraptocenter span {
display: inline-block;
height: 100%;
}
</style>
<!--[endif]-->
<div class="wraptocenter"><span></span><img src="..." alt="..."></div>