skip to Main Content

I have an outer div with hover effects and a button inside. I am trying to disable the hover effect on the outer div when I hover over the inner button but am failing to do so.

.container {
  background-color: #e6e6e6;
  width: 400px;
  height: 400px;
  margin: 0 auto;
  position: relative;
  text-align: center;
  align-items: center;
  border: 1px solid black;
}

.container:hover {
  border: 1px solid #99ffcf;
  background-color: #bababa;
}

button {
  padding: 10px;
  margin-top: 170px;
}

button:hover {
  cursor: pointer;
}
<div class="container">
  <button type="button">Click Me!</button>
</div>

Codepen Demo:
https://codepen.io/sherbethead/pen/LYMboRG

2

Answers


  1. If you are looking for a CSS only solution you can do so by replacing the container:hover by the below block

    .container:has(:not(button:hover)):hover{
      border: 1px solid #99ffcf;
      background-color: #bababa;
    }
    

    However do note that :has is not universally supported by browers, so please check it is supported by the browsers you need over on Can I use

    .container {
      background-color: #e6e6e6;
      width: 400px;
      height: 400px;
      margin:0 auto;
      position: relative;
      text-align: center;
      align-items: center;
      border: 1px solid black;
    }
    
    .container:has(:not(button:hover)):hover{
      border: 1px solid #99ffcf;
      background-color: #bababa;
    }
    
    button{
      padding: 10px;
      margin-top: 170px;
    }
    
    button:hover{
      cursor: pointer;
    }
    <div class="container">
      <button type="button">Click Me!</button>
    </div>
    Login or Signup to reply.
  2. Yue can add .container { pointer-events: none; } and button { pointer-events: auto; }:

    .container {
      background-color: #e6e6e6;
      width: 400px;
      height: 400px;
      margin: 0 auto;
      position: relative;
      text-align: center;
      align-items: center;
      border: 1px solid black;
      pointer-events: none;
    }
    
    .container:hover {
      border: 1px solid #99ffcf;
      background-color: #bababa;
    }
    
    button {
      padding: 10px;
      margin-top: 170px;
      pointer-events: auto;
    }
    
    button:hover {
      cursor: pointer;
    }
    <div class="container">
      <button type="button">Click Me!</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search