Home > Mobile >  HTML CSS - Button not returning to initial state after click
HTML CSS - Button not returning to initial state after click

Time:08-19

I am trying to implement a counter, but right now I'm only working with HTML, CSS and Bootstrap.

<button > </button>
.btn-purple {
   background-color: var(--purple);
   color: var(--white);
}

.btn-purple:hover {
   background-color: var(--green);
}

The problem is that when I click my button its background-color disappears and only appears again when I click somewhere else on the page.

The three states of the button: before click, hover and after click

I tried the following code, and it works at first glance, but now the button isn't "clickable" anymore, it stays red (only used for test purpose) and doesn't change color when hovered. As before, it only returns to purple and allows hover when I click elsewhere.

.btn-purple:focus {
   background-color: red;
}

Is there a way to make the button accepts multiple clicks, always staying purple and only changing when hovered (which was the initial state)?

CodePudding user response:

It seems this is an issue with Bootstrap on MacOS and Chrome.

You may do something like below to remove the focus:

<a  onclick="this.blur();"> </a>

Reference: How to remove focus around buttons on click

CodePudding user response:

Yes, you could try multiple psuedo-classes for the button.

.btn-purple:focus:hover {
  background: red;
}

.btn {
  cursor: pointer;
}

.btn-purple {
   background-color: purple;
   color: white;
}

.btn-purple:hover {
   background-color: red;
}

.btn-purple:focus {
  background: purple;
}

.btn-purple:focus:hover {
  background: red;
}
<button >-</button>
<button > </button>

CodePudding user response:

button:focus means the button will remain in focus (and not clickable) until you click another element.

button:active applies when the button is being activated. So, if you want your button (or any element) to have a particular colour when clicked, you use the pseudo-class.

I guess you can do something like this:

.btn-purple {
   background-color: purple;
}

.btn-purple:hover {
   background-color: green;
}

.btn-purple:active{
  background-color: purple;
}
<button > </button>

Read more here

  • Related