如何垂直居中图片?

3

我想找一种方法来垂直居中图像,类似于 text-align center 的效果。 text-align center 很有效,因为您不需要指定父元素的宽度或子元素的宽度,它会自动居中其内容。有没有其他方法来实现垂直定位图像?


你可以随时使用 vertical-align: middle - Vucko
请展示一些代码。你尝试过什么,但没有成功? - mavrosxristoforos
我还没有尝试过任何事情,因为我不知道该怎么做。 - user2310422
谷歌搜索“css垂直居中图像”有1.48亿个结果,你一个都没试过吗? - mavrosxristoforos
如何垂直对齐图像 - mavrosxristoforos
5个回答

4
你可以用两种方法来实现。第一种方式(首选),使用"display: table-cell"属性。
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 */
}

Demo 2


@Mr.Alien 还可以参考绝对居中,这将有助于完善答案。 - hitautodestruct
@hitautodestruct 不一定,但我已经添加了“首选”这个词 :) - Mr. Alien
@Mr.Alien 还可以参考 Chris Coyer 的这个技巧 - hitautodestruct

0

你现在的解决方案适用于旧版浏览器,但在不久的将来(现在已经有大约70%的浏览器支持)你可以使用一个更简单、更优雅的解决方案:

.container img{
  width: 100%;
  height: auto;
}
@supports(object-fit: cover){
    .container img{
      height: 100%;
      object-fit: cover;
      object-position: center center;
    }
}

0
div{
    display:table-cell;
    vertical-align:middle;
}

0

在父级 div 中设置 id 为 parentDiv,将图像设置为背景

#parentDiv
{
background:url(image.png) no-repeat center center;
height:500px;
width:500px;
}

或者在子div中执行这个操作...

position:absolute;
   top:50%;

0

所有的都在中间...

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

http://jsfiddle.net/djwave28/PD6J4/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接