css - 使用 css 将图像在图形内的链接内垂直居中

标签 css html wordpress-theming vertical-alignment

所以我尝试使用 CSS 自定义我的 WordPress 主题中的 slider 。现在,它并排显示三个帖子缩略图。不幸的是,我的特色图像都有不同的长宽比,因此我尝试通过为包含图像的 div 提供固定大小(202 像素 x 138 像素)和黑色背景,然后将图像居中来创建一种信箱效果该div。

这就是我想要的样子:

enter image description here

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

这就是现在的样子:

enter image description here

我已经很接近了。我已经阅读了垂直对齐(我已经看过“如何不垂直居中内容”博客文章[由于我的声誉不佳,我无法链接到该文章],该文章很有用且内容丰富,但没有解决我的问题),但此时我陷入困境。

我的 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的指示。然而,我的图像仍然快乐地坐在容器的顶部。我认为问题是图像位于链接标签内?或者可能与容器有关?我不知道。谁能帮我?

最佳答案

我删除了 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;
}

关于css - 使用 css 将图像在图形内的链接内垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20228491/

相关文章:

html - 如何防止浏览器窗口调整大小时 block 偏移发生 1-2px 的变化

html - 搜索输入和按钮未正确水平对齐

php - 在 WordPress 的非 Divi 页面中加载 Divi 库组件

html - 背景图像宽度为屏幕的 75%

css - 具有子项的纯 CSS 菜单下拉箭头

javascript - 如何在 React 中有条件地渲染图像?

php - ContactForm7 上 div 内输入的 WordPress 问题

html - 如何在 React 中构建高级过滤器组件?

javascript - 无法命名函数 "animate"是什么原因?

javascript - js脚本文件中的WordPress路径url