![](/img/trans.png)
[英]Make hovering over a parent element only affect its own text, not child elements
[英]hover affects all elements in class, how to make it only affect the one I'm hovering over?
我有一個菜單欄,上面有各種按鈕,當我將鼠標懸停在它們上面時,它們會略微下拉並更改顏色。
更改顏色效果很好,但是當我將鼠標懸停在一個按鈕上時,所有按鈕都會下拉(而不僅僅是我正在懸停的按鈕)。
HTML:
<div id="menu">
<div id="Button1" class="menuButton"></div>
<div id="Button2" class="menuButton"></div>
<div id="Button3" class="menuButton"></div>
</div>
CSS:
#menu {
display: block;
float: right;
position: absolute;
top:0;
left:0;
height: 30px;
}
.menuButton {
width: 36px;
height :40px;
position: relative;
display: inline-block;
margin-top: -10px;
background-color: rgba(200,50,50,0.25);
transition: margin-top .3s, background-color .3s;
}
.menuButton:hover {
margin-top: 0;
background-color: rgba(100,100,255,0.6);
}
誰能弄清楚為什么會發生這種情況(以及我能做些什么,所以只有我懸停的元素下降了)?
JSFiddle: http : //jsfiddle.net/howkx1nv/
您的外部容器高度為30px,而按鈕為40px,但底邊距為負。
將鼠標懸停在其中一個按鈕上時,它將失去其上邊距,從而將外部容器的高度拉伸到+ 10px,這將導致您所有其他按鈕填充整個40px。
話雖這么說,代碼中的罪魁禍首似乎是內聯塊的使用,因為塊之間的行為會相互關聯。 如果僅將display: inline-block
更改為float: left
放在原始小提琴中,您將看到正確的行為。
我已經更新了您的jsFiddle以完成您想要的: http : //jsfiddle.net/howkx1nv/1/
.menuButton {
width: 36px;
height :40px;
position: relative;
display: inline-block;
margin-top: -10px;
background-color: rgba(200,50,50,0.25);
transition: top .3s, background-color .3s;
}
.menuButton:hover {
position:relative;
top:10px;
background-color: rgba(100,100,255,0.6);
}
SquareCat解釋了為什么所有div都一起偷看的現象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.