Abhishek
Abhishek

Reputation: 4340

How to override CSS :hover?

I have this HTML code:

<ul>
    <li>Line 1</li>
    <li class="disabled">Line 2</li>
</ul>

And the corresponding CSS is:

ul li:hover {
    color: red;
}

This allows for both lis to be hovered over and have their color changed. But if I want one of them to be disabled, I’d use the following:

.disabled {
    color: grey;
}

But the other CSS code’s hover pseudo-class still has effect. Is there any way I can override this?

Upvotes: 32

Views: 83516

Answers (7)

Jon P
Jon P

Reputation: 19772

Change your CSS To:

ul li:hover{
    color:red;
}

.disabled ,.disabled:hover{
    color:grey;
}

See this fiddle

Updating for the 2020s, you can now use :not to your advantage

.disabled {
    color:grey;
}

ul li:not(.disabled):hover{
    color:red;
}
<ul>
    <li>Line 1</li>
    <li class="disabled">Line 2</li>
</ul>

Upvotes: 11

Ruxta
Ruxta

Reputation: 696

The first rule overrides it because of CSS specificity, i.e. it's more specific.

Change second rule to:

ul li.disabled, ul li.disabled:hover{
    color:grey;
}

Upvotes: 47

Madhukar Upadhyay
Madhukar Upadhyay

Reputation: 1

You can just do following in the css to discard any color for disabled elements while we hover on it.

ul li:hover:not(:disabled) {
        color: red;
    }

This will cause the color red to be applied only when list is not disabled.

Upvotes: -1

Denis Chenu
Denis Chenu

Reputation: 821

Minimum, if only need grey at every time, no need :hover on .disabled

ul li:hover{
  color:red;
}
ul li.disabled{// Last rule precedence
   color:grey;
}

Or for speed updating, use !important:

.disabled{
  color:grey !important;
}
ul li:hover{
   color:red;
}

Upvotes: -1

Matt Roy
Matt Roy

Reputation: 1525

I was trying to get a CSS "disabled" effect to be applied automatically when doing the following javascript:

  document.getElementById("TheButton").disabled = true;

If "TheButton" is defined with the class "TheClass":

  .TheClass { background-color: LightBlue; }
  .TheClass:hover { background-color: Cyan; }

The only thing that worked for me was with this CSS:

  .TheClass[disabled]            { background-color: lightgrey; } /* for IE */
  .TheClass[disabled='disabled'] { background-color: lightgrey; } /* for Chrome */
  .TheClass[disabled]:hover            { background-color: lightgrey; } /* for IE */
  .TheClass[disabled='disabled']:hover { background-color: lightgrey; } /* for Chrome */

Upvotes: -1

user529649
user529649

Reputation:

You just need to change your css:

ul li:hover{ color:red; }

ul li.disabled,ul li.disabled:hover{ color:grey; }

You have to disable the hover effect, so you give it the same color as when it wasn't hovered.

Upvotes: 1

hazzik
hazzik

Reputation: 13344

.disabled{
    color:grey !important;
}

Upvotes: 0

Related Questions