Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS trigger hover only for top element

Tags:

css

Is there elegant solution to hover only for top element, not for underlying; or i should to do this using javascript?

<div class="WithHover1">
   <div class="WithHover2">
       I am Top and I want to be the only div hightlighted
   </div>
   I want to be hightlighted too, but I dont want to be hightlighted when the nested one is
</div>
like image 655
WildDev Avatar asked Apr 25 '26 08:04

WildDev


2 Answers

You can't do this in just CSS, yet. The has selector is in draft for level 4/5 (I forget) CSS selectors, which will be awesome.

For now, javascript/jquery would be the easiest and most practical method.

$(".WithHover2").mouseover(function() {
    $(".WithHover1").removeClass("highlight");
    $(this).addClass("highlight");
});
like image 197
Jack hardcastle Avatar answered Apr 27 '26 01:04

Jack hardcastle


Here's a CSS3 solution, using the ::after pseudo-element, with a bottom border that overrides the background color of the bottom text.

The negative z-index prevents the border from covering up the text, and overflow: hidden prevents WithHover1 from expanding due to the large border.

It works in IE11 (at least), Chrome, Firefox, Safari, and Opera:

div.WithHover1 {
  font: 14px verdana;
  position: relative;
  overflow: hidden;
}

div.WithHover1:hover {
  background: yellow;
  position: relative;
  z-index: 1;
}

div.WithHover2:hover {
  background: orange;
}

div.WithHover2:hover::after {
  content: '';
  display: block;
  position: absolute;
  border-bottom: 1000px solid white;
  width: 100%;
  z-index: -1;
}
<div class="WithHover1">
  <div class="WithHover2">
    I am Top and I want to be the only div highlighted
  </div>
  I want to be highlighted too, but I dont want to be highlighted when the nested one is.
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>
like image 41
Rick Hitchcock Avatar answered Apr 27 '26 01:04

Rick Hitchcock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!