CSS on parent hover keep child not filter-grayscal

2019-02-28 11:33发布

问题:

I have two blocks- parent and child. On hover- parent block change grayscale. How can i keep child div with green color on hover (not grey, but green)?

<style>
.parent {
   color:red
   width: 100px;
   height: 100px;
}
.child {
   color: green
   width: 50px;
   height: 50px;
}
.parent:hover {
   filter: grayscale(100%)
}
</style>

<div class="parent">
   <div class="child">
   </div>
</div>

回答1:

I couldn't think of direct way, but here is an workaround using absolute positioning.

<style>
  .wrapper {
    position: relative
  }
  .parent {
    background-color: red;
    width: 100px;
    height: 100px;
  }
  .child {
    background-color: green;
    width: 50px;
    height: 50px;
    position: absolute;
    top: 0;
    left: 0;
  }
  .parent:hover {
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
  }
</style>
<div class="wrapper">
  <div class="parent">
  </div>
  <div class="child">
  </div>
</div>



回答2:

No. All child elem to be grayscalled. But try this:

.parent {
  width: 100px;
  height: 100px;
  position: relative;
}
.childbg {
  background-color: red;
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 0;
}
.child {
  background-color: green;
  width: 50px;
  height: 50px;
  position: absolute;
  z-index: 10;
}
.parent:hover > .childbg {
  filter: grayscale(100%);
  -webkit-filter: grayscale(100%);
}
<div class="parent">
  <div class="childbg"></div>
  <div class="child"></div>
</div>



回答3:

.granny {
  width: 100px;
  height: 100px;
}

.parent {
  color: red; width: 100px;
  height: 100px;
}

.child {
  position: absolute;
  color: green width: 50px;
  height: 50px;
}

.parent:hover {
  filter: grayscale(100%)
}
<div class="granny">Granny
  <div class="parent">Parent</div>
  <div class="child">Child</div>
</div>



回答4:

Since you've added more code, I'm not sure exactly what you're trying to achieve but this should not apply the filter to the child.

.parent+child :hover {
   filter:none;
}


标签: css hover