svecax svecax - 4 months ago 6
jQuery Question

Translate jQuery code to CSS or LESS

Is it possible to translate this code from jQuery to CSS or LESS?

$('li').mouseover(function() {
if ($('li ul li ul li:hover').length) {
$('li ul li ul li:hover').css('background', 'red');
} else if ($('li ul li:hover').length) {
$('li ul li:hover').css('background', 'red');
} else {
$('li:hover').css('background', 'red');
$('li').mouseout(function() {
$(this).css('background', 'transparent');

This code is used to hover the elements in a list like here: JSFIDDLE


If I understand correct, you want a pure CSS solution (without jQuery).

Well, it's possible.

The problem is that using a background on the li:hover will also color the children. But when hovering the children, the hover also effects the parent li.

So you'll need to wrap the text in a <span>:

li span {
  display: block;
li span:hover,
li span:hover~ul {
  background: red;
  <li><span>Item 1</span></li>
      <li><span>Item 2</span>
          <li><span>Item 2.1</span></li>
          <li><span>Item 2.2</span></li>
      <li><span>Item 3</span></li>