0

I want the color of a button to transition every time it's clicked. In the code snippet below, it transitions from green to blue.

The problem is that once the button has focus, the color doesn't change no matter how many times it's clicked. To reenable the effect I have to click somewhere else to make the button lose focus.

I thought the button:active event would reset the process every time the button was clicked, but that doesn't seem to be the case.

button {
  background: red;
  color: black;
  height: 50px;
  width: 100px;
}

button:active {
  background: green;
}

button:focus {
  background: blue;
  transition: all 3s ease;
}
<button>Click Me</button>
Philipp Bammes
  • 525
  • 1
  • 6
  • 25
guest856
  • 171
  • 2
  • 11

1 Answers1

1

You should perhaps look at the order of your pseudo classes (:focus/:active)

:active should always be the last in order!

There are some articles out on CSS-Pseudoclasses and their right use and order.

I took this from W3schools (https://www.w3schools.com/css/css_pseudo_classes.asp):

Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective! a:active MUST come after a:hover in the CSS definition in order to be effective! Pseudo-class names are not case-sensitive.*

:focus usually is similarly positioned as :hover (as hover only works with a mouse)

slee423
  • 1,307
  • 2
  • 20
  • 34
Andreas
  • 51
  • 4
  • Thanks! I still doesn't work quite as intended, because the :focus part doesn't reset, but after reordering the :active part is always activated. – guest856 Oct 24 '18 at 08:03
  • I didn't test it... Perhaps you find an answer here: https://stackoverflow.com/questions/39741709/css-focus-not-working – Andreas Oct 24 '18 at 15:39