232
votes

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?

7

7 Answers

416
votes

You can use :enabled pseudo-class, but notice IE<9 does not support it:

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

You can try this..

36
votes

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

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

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);
    }
  }
}
15
votes

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;
  }
}
15
votes

Use the lightest touch: overriding via rule order.

.btn {
  /* base styles */
}

.btn:hover {
  color: red;
}

.btn:active {
  color: green;
}

.btn:disabled {
  color: #aaa;
}

The trick is the order -- apply all the non-disabled states first, makes sure they all have the same specificity, and do disabled last, with the same specificity.

This won't work for a class added to links, or non-interactive elements, which don't have the disabled property.

(Edited to remove higher-specificity rules, and messing with pointer-events)

2
votes

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.