0

Let's take this example code below:

/*ul:first-of-type li a { color: red;}
ul > li a { color: red;}
ul:first-child li a { color: red;}*/
<ul>
 <li><a href="">Text</a></li>
 <li><a href="">Text</a></li>
 <li><a href="">Text</a></li>
 <li>
  <a href="">Text</a>
  <ul>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
  </ul>
 </li>
 <li><a href="">Text</a></li>
</ul>

My Goal here is to select the a tags that are within the parent ul tags, but not the ul that is nested within li.

I have read multiple articles about this but unfortunately couldn't find a solution to do this via CSS.

Can anyone please take a look into this?

iSaumya
  • 1,503
  • 5
  • 21
  • 50

2 Answers2

3

The CSS below will only select direct li children and within them, only direct a children. Since the second ul is a child of an li, its children will not be selected. It would require the following to select the hyperlinks in the second ul:

ul > li > ul > li > a

ul.main > li > a {
  color: red;
}
<ul class="main">
  <li><a href="">Text</a></li>
  <li><a href="">Text</a></li>
  <li><a href="">Text</a></li>
  <li>
    <a href="">Text</a>
    <ul>
      <li><a href="">Text</a></li>
      <li><a href="">Text</a></li>
      <li><a href="">Text</a></li>
      <li><a href="">Text</a></li>
      <li><a href="">Text</a></li>
    </ul>
  </li>
  <li><a href="">Text</a></li>
</ul>
Gerard
  • 15,418
  • 5
  • 30
  • 52
1

This should only target li's nested one level deep

ul > li > a 

But if not then override this style for the second level ul

ul li ul li a

ul > li > a { color: red;}
ul li ul li a { color: black;}
<ul>
 <li><a href="">Text</a></li>
 <li><a href="">Text</a></li>
 <li><a href="">Text</a></li>
 <li>
  <a href="">Text</a>
  <ul>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
   <li><a href="">Text</a></li>
  </ul>
 </li>
 <li><a href="">Text</a></li>
</ul>
Pixelomo
  • 6,373
  • 4
  • 47
  • 57
  • But I don't wanna use `ul li ul li a { color: black;}` this segment. Is there no way to target the `li` under parent `ul` without overwriting the nested `ul` css? – iSaumya Apr 17 '18 at 06:32
  • what is your top level ul inside of? try targeting it like this parentDiv > ul li a{color: red}. this should only target the top level ul, but you may also need to style the inner ul if it inherits the style. – Pixelomo Apr 17 '18 at 06:37
  • the parent `ul` is within `nav.navigation` and I have tried what you suggested, but didn't worked: https://jsfiddle.net/fL1v1p6v/5/ – iSaumya Apr 17 '18 at 06:42