1
votes

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>
3

3 Answers

6
votes

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
3
votes

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

0
votes

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! =)