0

I am trying to change the background of the list item when the focus is on the anchor tag. It works on hover, How can I change the background during focus?

I want to make the list more accessible so that even when the user focuses on the anchor tag, the respective list item should also highlight

.main-list{
  padding: 10px;
  margin: 0 10px;
}

.main-list .list-item{
  list-style-type: none;
  background: #ccc;
  padding: 10px;
  border-bottom: 1px solid #333;
  cursor: pointer;
}

.main-list .list-item:hover, .main-list .list-item:focus{
  background: #ddd;
}
<ul class="main-list">
 <li class="list-item"><a href="#">dummy text</a></li>
 <li class="list-item"><a href="#">dummy text</a></li>
 <li class="list-item"><a href="#">dummy text</a></li>
 <li class="list-item"><a href="#">dummy text</a></li>
</ul>
Pardeep
  • 1,546
  • 1
  • 11
  • 28
bhansa
  • 6,166
  • 2
  • 23
  • 42
  • 1
    If you want to consider focus of `a` (duplicate 2 (here: https://stackoverflow.com/a/46406959/8620333) and 3) ... If you want the focus on li (duplicate 1) – Temani Afif Aug 30 '19 at 12:48

1 Answers1

1

Use focus-within. Disclaimer: how compatible do you need it to be?

.main-list{
  padding: 10px;
  margin: 0 10px;
}

.main-list .list-item{
  list-style-type: none;
  background: #ccc;
  padding: 10px;
  border-bottom: 1px solid #333;
  cursor: pointer;
}

.main-list .list-item:hover, .main-list .list-item:focus-within{
  background: #ddd;
}
<ul class="main-list">
 <li class="list-item"><a href="#">dummy text</a></li>
 <li class="list-item"><a href="#">dummy text</a></li>
 <li class="list-item"><a href="#">dummy text</a></li>
 <li class="list-item"><a href="#">dummy text</a></li>
</ul>
Mr Lister
  • 42,557
  • 14
  • 95
  • 136