Home > Back-end >  How to not apply CSS :hover to parent elements
How to not apply CSS :hover to parent elements

Time:07-31

I want :hover not to be applied to parent elements, and when :hover is applied to the child, it also applies to parent divs.

div{
  min-width:50px;
  min-height:50px;
  padding:12px;
  background:#0002;
}

div:hover{
  background:#f204;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div> It work correct
    <div> how to hover this and parents don't not change back color
        <div> how to hover this and parents don't not change back color </div>
    </div>
</div>

</body>
</html>

CodePudding user response:

You have to use a more specific selector and cannot simply use div:hover. Try something like this:

div {
  min-width:50px;
  min-height:50px;
  padding:12px;
  background:#0002;
}

div > div > div:hover{
  background:#f204;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div> It work correct
    <div> how to hover this and parents don't not change back color
        <div> how to hover this and parents don't not change back color </div>
    </div>
</div>

</body>
</html>

This > is called child combinator: https://www.w3.org/TR/selectors/#child-combinators

CodePudding user response:

Add a class on the parent only and apply hover only on that class

  • Related