Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

With the following html, when I hover over child, I get a green background on parent. How can I stop that from happening? I do want the green background if I am hovering outside of the child element.

CSS3 is fine.

.parent {
  padding: 100px;
  width: 400px;
  height: 400px;
}

.parent:hover {
  background-color: green;
}

.child {
  padding: 100px;
  width: 200px;
  height: 200px;
}

.child:hover {
  background-color: blue;
}
<div class="parent">
  <div class="child">Child</div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

So this is REALLY ugly, but it works (kind of). I'm basically creating a duplicate of parent as a sibling of child. parent-overwrite is hidden by default, then displayed on the hover of child. Chrome doesn't like it unless you use the + selector instead of the ~ selector. This isn't very scalable, but it may work.

As the other guys posted, javascript would likely be a better solution.

 <style>
  .parent { padding: 100px; width: 400px; height:400px; position: relative; z-index: 998; }
  .parent:hover { background-color: green; }
  .child { padding: 100px; width: 200px; height:200px; position: relative; z-index: 1000; }
  .child:hover { background-color: blue; }
  .parent-overwrite { padding: inherit; width: inherit; height: inherit; position: absolute; top: 0; left: 0; z-index: 999; background-color: #FFF; display: none; }
  .child:hover ~ .parent-overwrite { display: block; }
</style>

<div class="parent">
    <div class="child">Child</div>
    <div class="parent-overwrite"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...