0

How do I set a background color to my <button> when it's clicked using css?

.myBtn {
    background-color: #fff;
    cursor: pointer;
    color: #000;
    text-decoration: none;
    text-transform: uppercase;
}

html:

<button type="button" class="myBtn">Highlight me when Clicked</button>
Becky
  • 5,467
  • 9
  • 40
  • 73

4 Answers4

3

Use the active selector for this. Here's a working FIDDLE.

.myBtn:active {
   background-color: #dd4814;
}

Check this for reference.

EDIT: You can use the focus selector also

.myBtn:focus {
    background-color: #dd4814;
}

But in this the color will change back again if the focus is lost from the button.

I guess you will need to take the help of Javascript or JQuery for changing the css rules on the click event of the button.

Community
  • 1
  • 1
Kunjan Thadani
  • 1,660
  • 3
  • 18
  • 26
1

Sorry - but I don't have the rep to comment. But I think this may answer your question: Change background on button click, using CSS only?

EDIT: Oops. That looks like it changes the entire background - but you could probably still use it but change

input[type="checkbox"]:checked + div{
    background: #5BC0DE;
}

to target the button by using the button class with something like this:

input[type="checkbox"]:checked + .mybtn{
    background: #5BC0DE;
}
Community
  • 1
  • 1
TBB
  • 1,207
  • 1
  • 14
  • 25
1

Edited answer:

<html>
<head>
<style>
.myBtn:active{
background-color: red;
}
.myBtn:visited{
background-color: red;
}

</style>
</head>
<body>
<button class ="myBtn">Click here to change bgcolor</button>
</body>
</html>
  • thanks for your answer. But I'm looking to do this in CSS (no js) as explained in my question. – Becky May 01 '15 at 06:31
  • Sorry, I did not see that. Please look at my edited answer: it uses CSS. Do you want the button's background color to turn red ONLY when the user clicks on it, or to stay red even after the user clicks it? If you want it red indefinitely, use that code, and if you want the red background color to wear off after the user stops clicking the button, remove the code with the "visited" pseudoclass. Hope this helps! –  May 01 '15 at 16:57
0

The following code is a snippet of SCSS.

:root {
  --b1: beige;
  --b2: brown;
  --b3: #654321;
}

#check {
  display: none;
}

.btn {
  background-color: var(--b2);
  padding: 5px;
  border: 1px solid var(--b3);
  font-family: Google Sans;
  font-weight: 600;
  color: var(--b1);
  outline: none;
  border-radius: 5px;
  cursor: pointer;
}

.btn:hover {
  background-color: darken(brown, 5);
  border: 1px solid darken(#654321, 10);
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
  • Welcome to StackOverflow! The question is about changing the color permanently on a button after it has been clicked. By using the :hover pseudo-selector the button will only change color when it's being hovered. – sunn0 Apr 14 '21 at 21:25