0

I have a DOM tree looking like that (let's say these are the class names):

  • container
    • my_label
    • my_span
    • my_sub-container

On hover on the container, my_label is displayed. The selector is .container:hover .my_label

I want to add another rule in order to hide my_label if my_sub-container is on hover as well.

How to apply a style to my_label if my_sub-container:hover is not the precedent or immediate sibling of my label ?

Billybobbonnet
  • 3,156
  • 4
  • 23
  • 49
  • 3
    There isn't one...CSS cannot select *up* the DOM. Plus, how do you hover two elements at the same time? It's not clear what you are really asking. Are you suggesting an alternative HTML structure...and if so, what? – Paulie_D Oct 30 '15 at 11:45
  • As @Paulie_D said, selecting up the dom isn't possible quite yet. However, this answer has a solution of sorts: http://stackoverflow.com/a/15503444/3909886 You could instead use jquery to find the label and hide it on hover of the sub-container, would you like that solution? – Sam Willis Oct 30 '15 at 11:52
  • 1
    @Paulie_D If you hover on a child element, the parent is hovered as well. What OP wants is to display `.my_label` if anywhere inside `.container` is hovered, **EXCEPT** `.my_sub-container` – Matheus208 Oct 30 '15 at 12:38
  • I know what he *wants* and it's not possible with CSS. – Paulie_D Oct 30 '15 at 13:07

2 Answers2

1

Such functionality cannot be achieved by CSS alone as CSS does not have backwards selectors. You want to use JavaScript/jQuery instead. Take a look at .hover() and show()/hide() or fadeIn()/fadeOut().

Justas
  • 519
  • 8
  • 18
1

Sadly, as Pauli_D says, you won't be able to do this with CSS, since it can't look "up" in the HTML, only down and inside itself.

A way to do this, is by adding a bit of jQuery and then telling with that what should be done. In my fiddle, I have added a .hover() that toggles a class and makes a div transparent. Check it out here.

jQuery

$(".my_sub-container").hover(function(){ //when hovered
    $('.my_label').toggleClass('hidden'); //do this
});

Of course, if you haven't added jQuery to your page yet, don't do it purely for this function, but use vanilla Javascript to do the same. It'll take a few more lines, but it beats adding a library for something this simple :D

Rvervuurt
  • 8,589
  • 8
  • 39
  • 62