看膩導航欄背景變色的hover
效果,我們看一下比較特殊的hover
效果。
分析
我們觀察到,當鼠標懸停在導航欄的項目中,出現從中間向左右展開的背景效果;移開時,又從左右向中間收縮??梢宰龀鋈缦路治觯?/p>
- 文字本身是沒有展開和收縮效果,說明文字與背景不是同一個元素。
- 文字在背景上面顯示,文字元素與背景元素是上下層關系,也就是存在定位。
- 背景展開和收縮有明顯的過渡效果。
實現
根據以上三點,我們逐個突破。
1. 文本元素與背景元素
- 文本元素
首先,文本使用span
標簽實現。加上寬高、居中等簡單樣式。 - HTML
<span>項目</span>
- CSS
span{
display: inline-block;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
}
- 背景元素
背景本身沒有具體意義,只是用來修飾,我們可以使用span
偽元素:after
實現(這樣可以減少一個專門表示背景的標簽)。 - CSS
span:after{
content: "";
background-color: #f00;
}
現在只能看到文字,還看不到背景色,因為背景元素沒有內容也沒有設置寬高。效果如圖:
只能看到文字,背景色沒有撐開
2. 在文本元素下面顯示背景元素
元素層疊效果一般是父relative
子absolute
實現。
- 文本元素
span{
display: inline-block;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
position: relative;
}
- 背景元素
span:after{
content: "";
background-color: #f00;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
z-index: -1;
}
注意:top: 0;bottom: 0;right: 0;left: 0;
作用是背景平鋪整個文本元素。
3. 鼠標懸停背景元素展開
背景元素開始時位于水平中間位置,也就是說距離左右是文本元素長度的一半。當鼠標懸停到文本元素上,背景展開。
- 背景元素初始狀態
span:after{
content: "";
background-color: #f00;
position: absolute;
top: 0;
bottom: 0;
right: 50%;
left: 50%;
z-index: -1;
}
- 鼠標懸停背景元素展開
span:hover:after{
right: 0;
left: 0;
}
鼠標懸停馬上顯示背景色,效果如同span:hover
直接改變顏色一致。我們還需要給背景元素加上過渡。
span:after{
content: "";
background-color: #f00;
position: absolute;
top: 0;
bottom: 0;
right: 50%;
left: 50%;
z-index: -1;
transition: 0.3s;
}
大功告成。
完整代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>項目</title>
<style>
span{
display: inline-block;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
position: relative;
}
span:after{
content: "";
background-color: #f00;
position: absolute;
top: 0;
bottom: 0;
right: 50%;
left: 50%;
z-index: -1;
transition: 0.3s;
}
span:hover:after{
right: 0;
left: 0;
}
</style>
</head>
<body>
<span>項目</span>
</body>
</html>
拓展
-
既然可以實現從中間向左右展開,是否可以實現從中間向上下展開?
-
能否可以實現單向展開呢?(從左向右,從右向左,從上向下,從下向上)
-
能否可以實現從中間向上下左右同時展開呢?
-
能否可以實現對角方向展開呢?
** 以上四個問題全部解決,恭喜你,鼠標懸停背景展開效果完全學會了。**
如有疑問歡迎留言