Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can hover on parent but not on child input

Basically I have

.parent {

  height:200px;

}

.title {

  user-select: none;

}

.parent:hover {

 background:green;

}
<div class="parent">
  <div class="title">
    Hello World!
  </div>
  <input type="text" placeholder="Hello Input!">
</div>

and I would like the hover effect to be disabled when hovering the input.

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One improvement would be to automatically disable the hover effect when cursor change to text or cursor.

>Solution :

You could use :not(:has(input:hover)) for a CSS-only solution, but please note that :has() is not supported universally in all browsers yet.

.parent {
  height:200px;
}

.title {
  user-select: none;
}

.parent:hover:not(:has(input:hover)) {
  background:green;
}
<div class="parent">
  <div class="title">
    Hello World!
  </div>
  <input type="text" placeholder="Hello Input!">
</div>

Otherwise, you could listen in JavaScript for whether the input is hovered:

const input = document.querySelector('input');

input.addEventListener('mouseenter', ({ target }) => {
  target.closest('.parent').classList.add('foo');
});

input.addEventListener('mouseleave', ({ target }) => {
  target.closest('.parent').classList.remove('foo');
});
.parent {
  height:200px;
}

.title {
  user-select: none;
}

.parent:hover:not(.foo) {
  background:green;
}
<div class="parent">
  <div class="title">
    Hello World!
  </div>
  <input type="text" placeholder="Hello Input!">
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading