I know that there does not exist a CSS parent selector, but is it possible to style a parenting element when hovering a child element without such a selector?
To give an example: consider a delete button that when hovered will highlight the element that is about to become deleted:
<div>
<p>Lorem ipsum ...</p>
<button>Delete</button>
</div>
By means of pure CSS, how to change the background color of this section when the mouse is over the button?
there is no CSS selector for selecting a parent of a selected child.
you could do it with JavaScript
As mentioned previously "there is no CSS selector for selecting a parent of a selected child".
So you either:
Here is the example for the javascript/jQuery solution
On the javascript side:
And on the CSS side, you'd have something like this:
I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).
If you set the parent to be with no
pointer-events
, and then a childdiv
withpointer-events
set toauto
, it works:)Note that
<img>
tag (for example) doesn't do the trick.Also remember to set
pointer-events
toauto
for other children which have their own event listener, or otherwise they will lose their click functionality.Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)
This is extremely easy to do in Sass! Don't delve into JavaScript for this. The & selector in sass does exactly this.
http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand
This solution depends fully on the design, but if you have a parent div that you want to change the background on when hovering a child you can try to mimic the parent with a
::after
/::before
.CSS:
See a full fiddle example here
Another, simpler approach (to an old question)..
would be to place elements as siblings and use:
Adjacent Sibling Selector (
+
) or General Sibling Selector (~
)Demo Fiddle here.