AvailableName
AvailableName

Reputation: 706

CSS selectors inside ul li

I have a ul/li menu that I'm trying to add :hover and :focus attributes to:

<ul>
  <li> <a href="/page1">Item 1</a></li>
  <li> <a href="/page2">Item 2</a></li>
  <li>
    <a href="/page3">
      <i class="fa fa-caret-down"></i>
      <span class="mobile-hidden">Item 3</span>
      <i class="fas fa-cogs"></i>
    </a>
  </li>
  <li>
    <a href="/page4">
      <i class="fa fa-caret-down"></i>
      <span class="mobile-hidden">Item 4</span>
      <i class="fas fa-user"></i>
    </a>
  </li>
</ul>

So using the following CSS I'm able to grab the first 2 items, but nothing of the latter 2. Adding additional selectors for the <span> and <li> tags doesn't seem to work.

ul li:hover, ul li:focus{
  color: #0077ff;
}

Upvotes: 1

Views: 906

Answers (2)

Willem van der Veen
Willem van der Veen

Reputation: 36580

To add to the previous answer:

ul li:hover a, ul li:focus a{

  color: #0077ff;

}
<ul>
  <li> <a href="/page1">Item 1</a></li>
  <li> <a href="/page2">Item 2</a></li>
  <li>
    <a href="/page3">
      <i class="fa fa-caret-down"></i>
      <span class="mobile-hidden">Item 3</span>
      <i class="fas fa-cogs"></i>
    </a>
  </li>
  <li>
    <a href="/page4">
      <i class="fa fa-caret-down"></i>
      <span class="mobile-hidden">Item 4</span>
      <i class="fas fa-user"></i>
    </a>
  </li>
</ul>

This code will have the following effect.

ul li:hover, ul li:focus{
  color: #0077ff;
}

The <a> tags will take up the space inside the <li> tags. Therefore when you put your mouse on the <li>. Therefore your mouse won't actually be on an <li> tag but on an <a> tag and thus the css rules won't work.

Upvotes: 0

kevinniel
kevinniel

Reputation: 1106

If you grab <ul> & <li> that's good. The problem is your <i> and <span> tags are inside a <a> tag. In these cases, the <a> styling always comes before its content.

So you'll have to make somthing like this :

ul li:hover a, ul li:focus a{
  color: #0077ff;
}

Upvotes: 4

Related Questions