18

So I have a div I want to change the color of when clicked. I have three divs over all and I want to denote which one is the active div when clicking on it

Basically I want to use the CSS active property but not have the particular div change back when the mouse up occurs. Sort of like a focus. I am also using bootstrap if that is helpful

Here is a example of the html

<div>
    Section 1
</div>
<div>
    Section 2
</div>
<div>
    Section 3
</div>

Could anyone tell me how i could accomplish this without using javascript?

mlwn
  • 1,156
  • 1
  • 10
  • 25
Philip Loyer
  • 738
  • 2
  • 7
  • 22
  • 1
    I didn't know if it could be done but I found this: http://tympanus.net/codrops/2012/12/17/css-click-events/ - give it a try? – blurfus Nov 21 '14 at 19:50
  • possible duplicate of [active(selected), hover and inactive tab/div css logic](http://stackoverflow.com/questions/6177636/activeselected-hover-and-inactive-tab-div-css-logic) – Chris W. Nov 21 '14 at 19:54
  • 2
    I think you can find the answer in [here][1] [1]: http://stackoverflow.com/questions/19260401/change-background-on-button-click-using-css-only – Ehsan Nov 21 '14 at 19:54
  • @Yuriy Galanter: I think I represent that case where a multiple selection is needed, like you mentioned in the comments with dave. This is the topic if you can help: [https://stackoverflow.com/questions/45346380/different-labeled-checkboxes](https://stackoverflow.com/questions/45346380/different-labeled-checkboxes) – John Galassi Jul 27 '17 at 10:14

4 Answers4

45

Make your DIVs focusable, by adding tabIndex:

<div tabindex="1">
Section 1
</div>

<div tabindex="2">
Section 2
</div>

<div tabindex="3">
Section 3
</div>

Then you can simple use :focus pseudo-class

div:focus {
    background-color:red;
}

Demo: http://jsfiddle.net/mwbbcyja/

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
6

Try this, it worked for me:

div:active{  

    background-color:white;

}
pheeleeppoo
  • 1,491
  • 6
  • 25
  • 29
Dhruv Naik
  • 141
  • 2
  • 2
0

:active is a great solution both for touch in mobile and click in pc. You can use :active to observe touch and use ::before for mask layer. Remember remove pointer event on ::before or ::before will intercept your click on div

div{
  position: relative;
}
div:active::before{
  content: "";
  position: absolute;
  top: 0; 
  left: 0;
  width: 100%; 
  height: 100%;  
  opacity: .4; 
  z-index: 5;
  background: rgba($color: #000000, $alpha: 0.12);
}
div::before{
  pointer-events: none;
}
Zane Li
  • 26
  • 4
-2
div:focus {
    background-color:'color';
}
mario
  • 17
  • 2