Search code examples
htmlcsshovermousehover

CSS mouse hover flickering issue


I'm new to CSS and I'm facing a problem. When the mouse moves over the input box, I want the text behind it to change color. But when the mouse moves over on it, flickering occurs.

How can I resolve the flickering without changing the following HTML structure?

.back:hover {
  color: red;
}

.my-input {
  position: absolute;
  top: 0px;
  opacity: 0.7;
  height: 30px;
}

.my-input:hover {
  pointer-events: none;
}

.my-input:focus {
  opacity: 1;
}
<div>
  <div class="back">
    Some text to be hovered even if input is above
  </div>
  <div>
    <input type="text" class="my-input" />
  </div>
</div>


Solution

  • pointer-events: none was only being applied while you were hovering over .my-input, and so the style was competing with it's own event. This style should be applied to the element by default

    .back:hover {
      color: red;
    }
    
    .my-input {
      position: absolute;
      top: 0px;
      opacity: 0.7;
      height: 30px;
      pointer-events: none;
    }
    
    .my-input:focus {
      opacity: 1;
    }
    <div>
      <div class="back">
        Some text to be hovered even if input is above
      </div>
    
      <div>
        <input type="text" class="my-input" />
      </div>
    </div>

    From Comment: If you're using jQuery, you can remove the pointer-events: none, as well as the :hover code, and keep the input intractable while still coloring the text

    $('.my-input').on({
      mouseenter: function() {
        $('.back').css('color', 'red');
      },
      mouseleave: function() {
        $('.back').css('color', '');
      }
    });
    .my-input {
      position: absolute;
      top: 0px;
      opacity: 0.7;
      height: 30px;
    }
    
    .my-input:focus {
      opacity: 1;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <div class="back">
        Some text to be hovered even if input is above
      </div>
    
      <div>
        <input type="text" class="my-input" />
      </div>
    </div>