Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On hover of child, change background color of parent container (CSS only)

Tags:

html

css

This is a common question. It almost always gets immediately closed as a duplicate of this question: Is there a CSS parent selector?

The duplicate does a good job pointing out that parent elements cannot be targeted with CSS. But it provides little to no guidance for the original question, which may be caught in the XY problem.

In this particular case...

How can the background color of the parent be changed when hovering the child?

...there is at least one CSS solution that may solve the problem.

<div>
  <a href="#">Anchor Text</a>
</div>
like image 948
Michael Benjamin Avatar asked Sep 07 '16 16:09

Michael Benjamin


1 Answers

Using just pointer-events and :hover

Compatibility of pointer-events: caniuse.com. Tested working on IE 11 and Edge, Chrome and Firefox.

  • Set pointer-events: none on the div. The div will now ignore :hover.

    div {
        pointer-events: none;
    }
    
  • Set the parent background to change on hover

    div:hover {
        background: #F00;
    }
    
  • Set pointer-events: auto on the child so that the hover event is triggered only when the child is hovered

    div > a {
        pointer-events: auto;
    }
    

This works because the div is hovered when its child is hovered, and pointer events are activated with auto only on that child. Otherwise the parent ignores its hover pseudo-class.

Example

Note: IE 11 and Edge require the child element to be display: inline-block or display: block for pointer events to work.

div {
  height: 200px;
  width: 200px;
  text-align: center;
  pointer-events: none;
}
div:hover {
  background: #F00;
}
div > a {
  pointer-events: auto;
  display: inline-block;
}
<div>
  <h1>Heading</h1>
  <a href="#">Anchor Text</a>
</div>
like image 176
misterManSam Avatar answered Oct 21 '22 03:10

misterManSam