CSS实现图片hover时半区域上滑展示内容的实现方法
图片hover上滑展示自定义内容实现方案
需求:将原有hover容器触发的上滑效果,改为鼠标hover在图片上时向上滑出展示自定义内容,同时适配无固定尺寸的图片场景。
原有代码(容器hover触发版)
CSS代码
h1 { margin: 0 } .box { height: 200px; width: 300px; overflow: hidden; border: 1px solid red; background: #ff0; } .hid-box { top: 100%; position: relative; transition: all .3s ease-out; background: #428bca; height: 100%; } .box:hover > .hid-box{ top: 80px; }
HTML代码
<div class="box"> <!-- <img src="pic1.png"> --> <div class="hid-box"> <h1>CSS3 slide up</h1> <p>This is a quick demo of slide-up effect using CSS animation when hover the box. No JS required!</p> </div> </div>
改造失效说明
原有方案使用固定尺寸的.box容器,在内部加入img标签改造后效果无法正常运行,不符合无固定尺寸图片的使用场景,失效代码如下:
失效CSS代码
h1 { margin: 0 } .box { height: 200px; width: 300px; overflow: hidden; border: 1px solid red; background: #ff0; } .hid-box { top: 100%; position: relative; transition: all .3s ease-out; background: #428bca; height: 100%; } .box:hover>.hid-box { top: 80px; } .box img { position: absolute }
失效HTML代码
<div class="box"> <img src="https://dummyimage.com/124x124/000/fff.png&text=pic1"> <div class="hid-box"> <h1>CSS3 slide up</h1> <p>This is a quick demo of slide-up effect using CSS animation when hover the box. No JS required!</p> </div> </div>
最终正确实现代码
该方案可自适应任意尺寸的图片,hover图片区域即可触发上滑效果:
CSS代码
.container { position: absolute; } .image { display: block; } .overlay { position: absolute; bottom: 0; left: 0; right: 0; background-color: green; color: white; overflow: hidden; width: 100%; height: 0; transition: .5s ease; } .container:hover .overlay { height: 50%; }
HTML代码
<div class="container"> <img src="https://dummyimage.com/120x120/000/fff.png&text=120x120" alt="Avatar" class="image"> <div class="overlay"> <div class="text">Hello World</div> </div> </div>
内容的提问来源于stack exchange,提问作者omkar
相关产品推荐
相关产品推荐

