我想找一种方法来垂直居中图像,类似于 text-align center
的效果。 text-align
center 很有效,因为您不需要指定父元素的宽度或子元素的宽度,它会自动居中其内容。有没有其他方法来实现垂直定位图像?
我想找一种方法来垂直居中图像,类似于 text-align center
的效果。 text-align
center 很有效,因为您不需要指定父元素的宽度或子元素的宽度,它会自动居中其内容。有没有其他方法来实现垂直定位图像?
div {
display: table-cell;
height: 100px;
border: 1px solid #f00;
vertical-align: middle;
}
方法2,使用position: absolute;
和top: 50%
,然后使用margin-top
减去图像总高度的1/2。
div {
height: 100px;
border: 1px solid #f00;
position: relative;
}
div img {
position: absolute;
top: 50%;
margin-top: -24px; /* half of total height of image */
}
你现在的解决方案适用于旧版浏览器,但在不久的将来(现在已经有大约70%的浏览器支持)你可以使用一个更简单、更优雅的解决方案:
.container img{
width: 100%;
height: auto;
}
@supports(object-fit: cover){
.container img{
height: 100%;
object-fit: cover;
object-position: center center;
}
}
div{
display:table-cell;
vertical-align:middle;
}
在父级 div 中设置 id 为 parentDiv,将图像设置为背景
#parentDiv
{
background:url(image.png) no-repeat center center;
height:500px;
width:500px;
}
或者在子div中执行这个操作...
position:absolute;
top:50%;
所有的都在中间...
<div id="container">
<div id="img"></div>
</div>
#container {
position: relative;
width:200px;
height:200px;
background:#040;
}
#container #img {
background: url("url_to_image.jpg") no-repeat center center;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}
vertical-align: middle
。 - Vucko