user1464139
user1464139

Reputation:

How can I make an <input> hover CSS work only if the <input> does not have focus?

I have an input field CSS like this:

input {
   background: white;
   border: 1px solid #bbb;
   box-shadow: none;
}

input:hover {
   background: white;
   border: 1px solid #999;
   outline: none;
   box-shadow: none;
 }

input:focus {
   outline: none;
   box-shadow: none;
   border: 1px solid #555;
}

My problem is that when I give the input focus the hover effect takes over if my cursor is also over the <input>.

Is there a way I can make the hover effect work only when the input does not have focus?

Upvotes: 1

Views: 681

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

With the code you've provided I can't reproduce the issue, which leads me to believe that this is a specificity problem. (If you're not sure what that is, I wrote a blog post about specificity earlier today: What the heck is specificity?)

With the code you've provided, both input:hover and input:focus have a specificity of 011. As long as input:focus is included after input:hover in your stylesheet then the focus style will always override the :hover.

First JSFiddle demo.

If your :hover has an extra selector, its specificity will be higher than the :focus selector. For instance:

input.example:hover { ... }
input:focus { ... }

Second JSFiddle demo.

With an extra class, the :hover selector above now has a specificity of 021 and will override the :focus selector which still has a lower specificity of 011.

Ensure your :focus selector has higher specificity and your :hover will not apply when the element is focussed.

Upvotes: 2

Related Questions