📜  如果子元素悬停,则更改容器 css 代码示例

📅  最后修改于: 2022-03-11 14:47:29.051000             🧑  作者: Mango

代码示例1
CSS can not select a parent div only when a specific child or descendent element is hovered.  You'll need some JavaScript to achieve what you seem to want.

JavaScript can be added to add something like a "hovered" class to your parent element when various mouse or touch events happen on the child div.  You could edit the CSS properties directly in JavaScript but I would use a CSS class just to keep more of the CSS concerns separate.



The :hover is closely related to your question but it doesn't solve your requirements.  :hover lets you select elements that are hovered over.  If the child is hovered, the parent is also hovered.  There is a problem though.
Here is an example of the problem with :hover:
HTML:
CSS: .my-parent:hover { background-color: green; } Say you want the background of my-parent to go red when hovering over "OK". The above example will do that. The problem is it'll go green when hovering over the Cancel button too.