Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

CSS :focus not working

Writer Emily Wong

I tried using :focus CSS pseudo-class in my project. I want to change the color of the element where I click on it. Now when I click my element change color only where it is active and after mouse up it return to old color. After second click I want it back to old color. I'm using Chrome.

Demo here

.row { display: inline-block; border: 1px solid grey; height: 200px; width: 200px; line-height: 1em; background: grey; margin: 5px; opacity: 0.1;
}
.row:active,
.row:focus { background: orange;
}
<div> <div> </div>
</div>
2

5 Answers

If you want a real focus state to a div element, you can add a tabindex attribute to it.

.row {	display:inline-block; border:1px solid grey; height:200px; width: 200px; line-height:1em; background: grey; margin: 5px; opacity: 0.1;
}
.row:active, .row:focus { background: orange; } 
<div>
<div tabindex="1">
</div>
</div>

If you want toggle the color with clicking the same div element, you have to use javascript (jQuery):

jQuery('#row0').click(function() { $(this).toggleClass('orange');
});
.row {	display:inline-block; border:1px solid grey; height:200px; width: 200px; line-height:1em; background: grey; margin: 5px; opacity: 0.1;
}
.row.orange { background: orange; }
<script src=""></script>
<div>
<div>
</div>
</div>
0

Following Andy Tschiersch's answer, I would suggest using tabindex = "0" (which is its default value) instead of tabindex = "1".

See:

<div> <div tabindex="0" > </div>
</div>

You can emulate the toggle effect with a CSS trick by adding a hidden checkbox input.

See it here

HTML :

<div> <input type="checkbox" /> <div> </div>
</div>

CSS :

.container { position: relative; }
input { position: absolute; left: 0; right: 0; top: 0; bottom: 0; width: 200px; height: 200px; z-index: 1; opacity: 0; display: block; }
input:checked + .row { background: orange; }
4
.row { display:inline-block; border:1px solid grey; height:200px; width: 200px; line-height:1em; background: grey; margin: 5px; opacity: 0.1;
}
.row:active, .row:focus { background: orange; opacity:1 }
<div>
<div tabindex="1">
</div>
</div>

Please try this...

What you are looking for is :visited, but this doesn't work on a div. You should use the a-tag for it (including href="#").

.row:active, .row:visited { background: orange; }

Check the fiddle below:

Edit: Vincent G's answer seems to do more what you want though, since you can remove the background color by clicking away.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy