[css] Hover and Active only when not disabled

I use hover, active and disabled to style Buttons.

But the problem is when the button is disabled the hover and active styles still applies.

How to apply hover and active only on enabled buttons?

This question is related to css

The answer is


In sass (scss):

 button {
  color: white;
  cursor: pointer;
  border-radius: 4px;

  &:disabled{
    opacity: 0.4;

    &:hover{
      opacity: 0.4;  //this is what you want
    }
  }

  &:hover{
    opacity: 0.9;
  }
}

Why not using attribute "disabled" in css. This must works on all browsers.

button[disabled]:hover {
    background: red;
}
button:hover {
    background: lime;
}

One way is to add a partcular class while disabling buttons and overriding the hover and active states for that class in css. Or removing a class when disabling and specifying the hover and active pseudo properties on that class only in css. Either way, it likely cannot be done purely with css, you'll need to use a bit of js.


A lower-specificity approach that works in most modern browsers (IE11+, and excluding some mobile Opera & IE browsers -- http://caniuse.com/#feat=pointer-events):

.btn {
  /* base styles */
}

.btn[disabled]
  opacity: 0.4;
  cursor: default;
  pointer-events: none;
}

.btn:hover {
  color: red;
}

The pointer-events: none rule will disable hover; you won't need to raise specificity with a .btn[disabled]:hover selector to nullify the hover style.

(FYI, this is the simple HTML pointer-events, not the contentious abstracting-input-devices pointer-events)


If you are using LESS or Sass, You can try this:

.btn {
  &[disabled] {
    opacity: 0.6;
  }
  &:hover, &:active {
    &:not([disabled]) {
      background-color: darken($orange, 15);
    }
  }
}

.button:active:hover:not([disabled]) {
    /*your styles*/
}

You can try this..