hover on child without hover effect on parent

EaterOfCode picture EaterOfCode · Jul 29, 2013 · Viewed 37.5k times · Source

So I have 2 div's they're in each other so like this

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

and I want to change the background from .parent when I hover over .parent.

but I want the background to turn normal again when I hover over .child.

so for example: (or http://jsfiddle.net/k3Zdt/1/ )

.parent {
    transition:background-color 1s;
    width:100px;
    height:100px;
    background:#3D6AA2;
    padding:50px;
}

.parent:hover {
    background:#FFF;
}

.child {
    height:100px;
    width:100px;
    background:#355E95;
    transition:background-color 1s;
}

.child:hover {
    background:#000;
}
<div class="parent">
    <div class="child">
    </div>
</div>

When I hover over the darkblue area I want the not-so-darkblue area to stay not-so-darkblue instead of changing to white.

I would like to keep this <div> structure. and I dont want a JavaScript solution (I know the JavaScript solution but I want to keep it pure CSS).

Answer

luxcem picture luxcem · Jul 29, 2013

Basically you can't : How to style the parent element when hovering a child element?

But a trick is to use a sibling element : http://jsfiddle.net/k3Zdt/8/

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

.child {
  height: 100px;
  width: 100px;
  background: #355E95;
  transition: background-color 1s;
  position: relative;
  top: -200px;
}

.child:hover {
  background: #000;
}

.sibling {
  position: relative;
  width: 100px;
  height: 100px;
  padding: 50px;
  top: -50px;
  left: -50px;
  background: #3D6AA2;
  transition: background-color 1s;    
}

.sibling:hover {
  background: #FFF;
}
<div class="parent">
    <div class="sibling"></div>
    <div class="child"></div>
</div>