Keavon
Keavon

Reputation: 7513

Style button when :active different from :hover

I want to make a button that displays a background color when hovering and a button color without a background color when the button is down. Here is my current code:

.windowButton:hover {
    background-color:#1a82b8;
}
.windowButton:active #windowClose polygon {
    fill:#1a82b8;
}

The problem with the above code is that it turns the icon a color when :active but doesn't remove the background color set by :hover. How do I remove the background color?

Upvotes: 0

Views: 19824

Answers (4)

Topher Rhodes
Topher Rhodes

Reputation: 95

In order for the active state to be applied while the user is also hovering over the button, it's necessary for the :hover selector to come before the :active selector in the code.

From https://developer.mozilla.org/en-US/docs/Web/CSS/:active:

Styles defined by the :active pseudo-class will be overridden by any subsequent link-related pseudo-class (:link, :hover, or :visited) that has at least equal specificity. To style links appropriately, put the :active rule after all other link-related rules, as defined by the LVHA-order: :link — :visited — :hover — :active.

While the accepted answer did mention that it's necessary to have :active come after :link and :visited, it doesn't say that it must also come after :hover (since in the example given in the question this was already the case). However this wasn't immediately clear to me, so I wanted to post this answer for anyone else who was stuck like I was because the :hover selector was coming after :active.

Also, I think the LVHA-order is a handy rule to keep in mind and relevant to this question.

Upvotes: 1

Samuel Archibong
Samuel Archibong

Reputation: 1

`button:hover{background-color: transparent;color: yellow;}

button:active {background: white;color: black;}`

Upvotes: -1

Emilio Gort
Emilio Gort

Reputation: 3470

You have to set a new background color on :hover state

.windowButton:hover {
    background-color:#1a82b8;
}
.windowButton:active {
   fill:#1a82b8;
   background-color:#000000;/*You can put the color you want*/
}

Pseudo states inherit values. For consistency purposes, it is best to only declare the styles which you are changing in your pseudo state rules.

Note: :hover MUST come after :link and :visited (if they are present) in the CSS definition, in order to be effective!

Upvotes: 4

Nikk
Nikk

Reputation: 7891

How about this?

I would guess, its cause on the first property you are using background-color and the second fill.

button:hover {
    background-color: red;
}
button:active {
    background-color: blue;
}

jsFiddle working example (1)

Upvotes: 2

Related Questions