【问题标题】:center content over image on hover悬停时将内容居中放在图像上
【发布时间】:2017-10-03 23:19:22
【问题描述】:

我有一个图片库。当图像悬停在图像的中心时,我想在图像的中心显示一段内容(照片在 instagram 上的点赞数)。此内容和图像是同一父元素下的兄弟姐妹,因此我尝试使用 position: relative;和底部:50%;在内容上。结果是内容(p.likes 的类)没有向上移动 50% 的父元素。为什么这不起作用?

.photo-box {
    width: 100%;
    display: inline-block;
    margin: 0 0 .75em;
    background-color: lightgrey;
    /*border: 1px solid pink;*/
}

.photo-box .image-wrap {
    width: 100%;
    height: auto;
    max-height: 100%;
    padding: none;
    background-color: lightgrey;
    /*border: 1px solid red;*/
}

.image-wrap img {
    width: 100%;
    display: inline-block;
    margin-bottom: 0px;
    padding: none;
}

.image-wrap:hover img {
    opacity: .8;
}

.image-wrap a {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: none;
}

p.likes {
    width: 100%;
    visibility: hidden;
    position: relative;
    bottom: 50%;
    text-align: center;
    font-family: 'Open Sans', sans-serif;
    color: #fff;
    /*border: 1px solid red;*/
}

.photo-box:hover p.likes {
    visibility: visible;
}
<div class="photo-box">
    <div class="image-wrap wow fadeIn">
        <a href="{{link}}" target="_blank">
            <img src="{{image}}">
        </a>
        <p class="likes"><i class="fa fa-heart" aria-hidden="true"></i> {{likes}}</p>
    </div>
</div>
    

【问题讨论】:

    标签: html css image


    【解决方案1】:

    父元素需要设置定位,以便子元素相对于容器移动。一种方法是首先在 .image-wrap 父 div 上添加 position: relative。然后,在.likes 类上,将相对定位替换为position: absolute

    我将您的代码添加到笔中以对此进行测试(并对其稍作修改),但这就是您想要的吗?我在那里扔了一个过渡,但你可以删除它并使用bottom 属性将它放在你想要的地方。另请注意,我为父级添加了静态高度。

    Pen

    【讨论】:

    • 谢谢!这正是我想要的。触感很好,也很轻松
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2014-01-18
    相关资源
    最近更新 更多