2

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>
Nayuki
  • 17,911
  • 6
  • 53
  • 80
cyberoy
  • 363
  • 2
  • 7
  • 18

3 Answers3

7

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
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
3

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

Community
  • 1
  • 1
grmdgs
  • 585
  • 6
  • 17
0

You can turn the element into a button.

remove default styling from a button:

online: none;
border: none;
background: none;

then apply the usual button :focus or :active selectors.

Here is example:

HTML:

<button>test1</button>
<button>test2</button>
<button>test3</button>

CSS:

button{
  width: 100px;
  height: 100px; 
  background: lightgray;
  outline: none;
  border: none;
}

button:hover{
  color: red; 
  cursor: pointer;
}

button:focus, button:active{
  background-color: pink;
  color: white; 
}

here is codepen for this: https://codepen.io/dmitrisan/pen/PomdRBG

REMEMBER: You can turn a BUTTON into a div or span tag, via CSS rules, but all BUTTON pseudo-selectors will still apply.

PROGRAMING IS EPIC! You make the RULES! =)

fruitloaf
  • 1,628
  • 15
  • 10
  • How is your answer different from the existing answers? The whole thing about buttons adds nothing to the discussion. – Ouroborus Aug 04 '21 at 22:02