21

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?

5

4 Answers 4

46

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/

Sign up to request clarification or add additional context in comments.

8 Comments

This works, as long as you don't have other items on the page that may take the focus.
Well if you click that other item - the DIV will lose focus and restore original style. If that's not intended behavior, OP should elaborate.
I tried this and like dave said as long as there are other things on the page it doesnt seem to work. Thanks though
Thank you this work. But I have a question Please how can I select a default one ?
and then you click outside of a div and you color is gone... how do you maintain the color without using js
|
8

Try this, it worked for me:

div:active{  

    background-color:white;

}

2 Comments

please improve your answer by adding a link to docu of :active pseudoselector
This doesn't work.
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;
}

Comments

-2
div:focus {
    background-color:'color';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.