在網頁開發中經常有需求是鼠標移動到一個元素A身上時,另外一個元素B顯示。 如下圖
當鼠標移到圖片上時,相關的描述從下方顯示出來。
css實現原理與情景:
- A 是 B 的父元素
- B 默認隱藏
B{opacity:0,transition: all 0.3s; transform: translateY(100%)}
- 當鼠標在A上時,即 A:hover狀態,B顯示 css實現即
A:hover B{opacity:1,translateY(0)}
示例代碼:
html
<li class="recommends-content-item">
<img src="../img/pages/home/img.png" alt="">
<div class="recommends-content-item__info">
<h3 class="ellipsis">標題1</h3>
<p class="ellipsis">描述描述描述描述描描述描述描述描述描述描述描述描述描</p>
</div>
</li>
css
.recommends-content-item{
width: 33%;
height: 280px;
margin-right: 1rem;
/* height: 15rem; */
background: #eee;
position: relative;
}
.recommends-content-item:hover .recommends-content-item__info{
opacity: 1;
transform: translateY(0);
}
.recommends-content-item__info{
position: absolute;
bottom: 0;
color: rgba(255, 255, 255, 0.8);
background: rgba(34,34,34,0.35);
padding: 0 0.5rem;
text-align: center;
overflow: hidden;
width: 100%;
box-sizing: border-box;
transition: 0.3s;
opacity: 0;
transform: translateY(100%);
}
當然,如果a、b元素有一個相同的父級,同樣的原理.father:hover .b { display:block } 就可以實現類似的效果了。