Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color of selected item using CSS

Tags:

html

css

I have a list of items. The user can select an item by clicking. I want to change the color of the selected item by using CSS. Suppose the user clicked on item1, then item1 will get red color. Now if user clicks on item 2, then item2 will get red color. My HTML code:

<ul>
  <li>item1</li>
  <li>item2</li>
  <li>item3</li>
</ul>
like image 786
cyberoy Avatar asked Nov 27 '25 14:11

cyberoy


2 Answers

Adding a tabindex to each li element allows you to apply a :focus pseudo-class:

li:focus {
  color: red;
  outline: none;
}
<ul>
  <li tabindex=1>item1</li>
  <li tabindex=1>item2</li>
  <li tabindex=1>item3</li>
</ul
like image 175
Rick Hitchcock Avatar answered Nov 30 '25 05:11

Rick Hitchcock


You can do this with just CSS by using the :focus pseudo selector:

li:focus{
  color:red;
  outline:none;
}

This requires the elements be focusable. Adding a tab index is probably appropriate for what you are doing and will work.

<ul>
  <li tabindex="0">item1</li>
  <li tabindex="0">item2</li>
  <li tabindex="0">item3</li>
</ul>

here is an answer about which elements recieve focus: Which HTML elements can receive focus?

http://jsbin.com/nokiyapejo/edit?html,css,js,output

like image 25
grmdgs Avatar answered Nov 30 '25 04:11

grmdgs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!