使用css将img垂直居中在图中的链接内

时间:2013-11-26 21:38:25

标签: html css html5 wordpress-theming vertical-alignment

所以我正在尝试使用CSS自定义我的wordpress主题中的滑块。现在,它并排显示三个帖子缩略图。不幸的是我的特色图像都有不同的宽高比,所以我试图通过给包含图像固定大小(202像素×138像素)和黑色背景的div创建一种信箱效果,然后将图像居中div。

这就是我想要的样子:

enter image description here

现在,我的所有图像都与容器的顶部对齐,所以看起来最短/最胖的图像底部只有一个黑条。

这就是它现在的样子:

enter image description here

我很亲密。我已经阅读了vertical-align(我已经看过“如何不垂直居中内容”博客文章[由于我可怕的声誉我无法链接],这是有用的和有用的,但没有解决我的问题),但此时我只是卡住了。

我的HTML看起来像这样:

<ul class="slider">
   <li>
       <figure class="slide-image">
           <a href="blogposturl">
               <img src="blogimage" />
           </a>
       </figure>

       //and then some other stuff//

   </li>
</ul>

然后是CSS!我的CSS现在看起来像这样:

.slider {
    position: relative;
}

.slider li {
    position: absolute;
}

figure.slide-image {
    border-radius: 0px;
    width: 202px;
    height: 138px;
    position: absolute;
    background-color: #000;
}

.slide-image img {
    border-radius: 0px;
    position: absolute;
    left: 0;
    max-width: 202px;
    top: 50%;
    margin-top: -69px;
}

我基本上遵循了phrogz的指示。然而,我的形象仍然快乐地坐在容器的顶部。我认为问题是图像在链接标签内?或者它可能与容器有关?我不知道。谁能帮我?

1 个答案:

答案 0 :(得分:2)

我删除了img上的一些绝对定位。请尝试这种方法:

它使用display:table-cellvertical-align:middle进行垂直居中。

Working example here - 正如您所看到的,它适用于不同的高度。我也没有改变任何HTML。

figure.slide-image a {
    display: table-cell;
    vertical-align: middle;
    height: 138px;
}
.slide-image img {
    border-radius: 0px;
    max-width: 202px;
    vertical-align: middle;
}